Python Introduction
Download
Report
Transcript Python Introduction
PYTHON INTRODUCTION
31 May 2012
Colin Sturm
OVERVIEW
Brief history
Why use Python?
Syntax, command line and scripting
Good programming techniques
Real examples
HISTORY AND BACKGROUND OF PYTHON
Guido van Rossum from Holland
Developed Python 1.0 in the late 1980s. Officially
released December 1989.
Python 2.0 released in 2000
Python 3.0 released in 2008
Name originates from Monty Python
Open source and free to use.
Any style of programming can be used:
E.g. object-oriented, structured, functional
WHY USE PYTHON?
Open source and free.
Scripting language for fast turn around.
No compiling which makes debugging easier and
faster.
Designed to be readable.
Cross platform functionality. Works natively on
Windows, Mac, and Linux
Python does a lot of the work for you
No need to declare variables, clean memory,
bookkeep
Many companies have built their programs with
Python:
Altair, Ensight, Dropbox, Civilization IV, Battlefield
2, Gmail backend, etc.
EXAMPLE: CREATE FAST COMPARISONS
EXAMPLE: COMPARE DATA WITH GRAPHS
EXAMPLE: LOAD VIDEO FOR COMPARISON
EXAMPLE: EXTRACT DATA QUICKLY
Need to download
specific files spread
over several
directories
Save the data locally
after located remotely
GET STARTED
Open Python terminal or command
prompt:
Either search for Python (command
line) from the start menu or
Start a command prompt using cmd
(better option because the working
environment will be in the directory
that python is started)
If typing python doesn’t work at the
command prompt then add the path as
shown in the image:
Control Panel -> system -> Advanced
system setting -> Environment variables
-> edit Path under system variables ->
add at the end of the line ;C:\Python27
(assuming you are using Python 2.7 and
it is located here). Save and reopen a
command prompt
PYTHON PROMPT
The prompt will look
similar to the image.
Commands can be
directly typed at the
prompt and executed
by pressing enter.
This environment can
be used to directly test
pieces of code.
To exit the
environment in
Windows OS use:
Ctrl-Z then enter
SYNTAX: TEXT AND MATH
text = “Hello World!”
print text
print text[1]
print text[-1]
print text[:3]
print len(text)
print text*3
print text + text
Mathematics
x=2; y=7
print x**2 + x*y + y**2 – x/y
y % x this is the modulus
10 % 6 evaluates to 4
SYNTAX: LISTS AND DICTIONARIES
Lists
people = [‘Matlock’, ‘Bussum’, ‘McDuff’, ‘Sheth’,
“Sturm”]
children = [2, 5, 0, 1, 0]
various = [‘States’, 50, [“Pi”, 3.1415926] ]
print sorted(people, reverse=True)
various.append(False)
various.pop()
various.insert(42, 1)
Dictionaries
family = {‘Matlock’: 4, ‘Bussum’: 7}
family[‘Matlock’]
for key in family: print key
for key, value in family.items(): print key, value
SYNTAX: LOOPS AND STATEMENTS
When evaluating a loop or if,then statement
Python requires indentation to designate start
and stop of the loop or statement. Typically 4
spaces are used.
if 2 == 2:
print “this statement is true”
print “a second line”
Code can also be written on a single line
if 2 in children: print “yes”
For multiple lines of code on the same line
separate using ;
if 2 in children: print “yes”; children.append(10)
Note: spacing is not required for single line code
SYNTAX: LOOPS AND STATEMENTS
The statement and loop example were written as text
and could be run from a file. If the same code were
written in the python environment command prompt
you would end the statement with a return on a blank
line.
Note: in the screenshot four spaces were used as the
indent. The same script would work if any number of
spaces were used for indent as long as the number is
consistent from line to line.
SYNTAX: LOOPS AND STATEMENTS
For loops can be of a range or a list. Technically a
range is a generated list of numbers.
for i in range(10): print i
for i in children: print i
While loop:
While condition uses the same syntax. While Do
is implemented using while true … break
While 2 == 2: print something
while True: print “True”; break
Opening files for input or manipulation
infile = open(“filename”,’r’)
print infile.read()
for line in infile: print line
infile.close()
SYNTAX: LOOPS AND STATEMENTS
Variables do not have to be declared directly but
can de useful to be explicit
var = int(3.14)
var = float(3.14)
User input is easily done at the prompt.
To be safer use raw_input which is not evaluated
directly and is saved as a string
user_text = input(“Enter a number: “)
user_text = raw_input(“Enter anything: “)
Code can be commented out or comments added
using # at the beginning of the comment
anywhere on the line.
FINDING HELP
http://docs.python.org/
Internet search / Text books
In the python environment:
import math
dir(math)
help(math)
Lists all of the possible functions in the math class
Details what each function in math does
help(math.function_name)
Details about function_name found in the math class
Ex: help(math.pow)
pow(x, y)
Return x**y (x to the power of y).
PROGRAMMING TECHNIQUES
PEP8 – python style guide
ALWAYS Make Comments
Add a header to programs – a quick definition of the program
################
## This program turns on the flux capacitor
## Written by Colin Sturm on 31/May/2012
################
Plenty of space, avoid dense code blocks
Useful variable names
Sometimes it’s annoying to add comments but comments will always help
later on. Even code that seems straight forward can become confusing on
what is exactly done as time passes.
Use start_time in place of st
Makes search and replace in code much easier
Consistent formatting
Constantly test while coding
Avoid hard coding constants, make everything a variable
Keep related code close together
CREATING A SCRIPT
Open a new file in your favorite text editor.
Preferably a text editor that has syntax highlighting (IDLE comes with
Python).
Enter the code you want to execute:
##########################################
## Find the sum of the digits for the number 2^100
## Written by Colin Sturm on 31/May/2012
##########################################
number = str(2**100)
sum_of_digits = 0
for i in number:
# sum_of_digits = sum_of_digits + int(i)
sum_of_digits += int(i)
OR
for i in range(len(number)):
# sum_of_digits = sum_of_digits + int(number[i])
sum_of_digits += int(number[i])
print sum_of_digits
Save the file as desired with extension py. (numsum.py)
EXECUTING A SCRIPT
At the command prompt:
python numsum.py
In the python environment ran from the desired
directory:
import numsum
or
execfile(‘numsum.py’)
In the environment you can type in variables from your
script to view the stored values:
number = '1267650600228229401496703205376'
To handle directories in the python environment:
import os
os.getcwd()
'/home/user‘
os.chdir("/tmp/")
os.getcwd()
'/tmp'
EXAMPLE: USING FOR LOOPS
Problem 1 (from projecteuler.net):
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of
these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
SOLUTION
######################################
#Find the sum of all the multiples of 3 or 5 below 1000.
######################################
count = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:count += i
print count
#answer: 233168
EXAMPLE: MORE LOOPS
Problem 2 (from projecteuler.net):
Each new term in the Fibonacci sequence is
generated by adding the previous two terms. By
starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence
whose values do not exceed four million, find the sum
of the even-valued terms.
SOLUTION
i=1
j=1
count = 0
while True:
if j % 2 == 0: count += j
temp = j
j = i+j
i = temp
if j >= 4000000:break
print count
# answer: 4613732
EXAMPLE: READING TEXT DATA
Problem 3 (from Colin Sturm):
Data is in the form:
Tue 05/29/2012 09:34:02.93 01
How many occurrences of 13 in the last column can be
found?
How
many01entries
for Wed?
Tue 05/29/2012
09:34:02.93
Wed 05/30/2012
12:52:34.38 03
Thu 05/31/2012 10:25:31.49 13
Tue 05/29/2012 12:18:00.49 11
Wed 05/30/2012 14:05:55.88 04
Thu 05/31/2012 11:01:20.94 11
Tue 05/29/2012 12:33:14.18 12
Wed 05/30/2012 14:38:29.20 13
Thu 05/31/2012 11:18:26.31 12
Tue 05/29/2012 13:11:45.67 13
Wed 05/30/2012 16:16:52.53 13
Thu 05/31/2012 11:56:39.87 13
Tue 05/29/2012 13:11:48.43 03
Wed 05/30/2012 17:11:50.93 13
Thu 05/31/2012 11:59:08.26 03
Tue 05/29/2012 13:59:49.59 04
Wed 05/30/2012 18:03:58.72 13
Thu 05/31/2012 13:07:45.51 04
Tue 05/29/2012 15:24:33.24 13
Wed 05/30/2012 18:11:13.24 02
Thu 05/31/2012 13:21:40.40 13
Tue 05/29/2012 16:17:20.54 13
Thu 05/31/2012 08:27:15.67 01
Thu 05/31/2012 15:04:22.63 13
Tue 05/29/2012 17:15:25.84 13
Thu 05/31/2012 08:27:15.67 05
Thu 05/31/2012 15:52:45.47 13
Tue 05/29/2012 17:50:15.45 13
Thu 05/31/2012 09:06:58.87 06
Thu 05/31/2012 17:11:12.89 13
Tue 05/29/2012 18:17:35.12 02
Thu 05/31/2012 09:28:33.20 05
Thu 05/31/2012 18:09:18.71 02
Wed 05/30/2012 09:23:38.48 01
Thu 05/31/2012 10:16:13.58 06
SOLUTION
count = 0
daycount = 0
infile = open('data.txt','r')
for line in infile:
line = line.split()
if line[3] == '13':
count += 1
if line[0] == 'Wed':
daycount += 1
print str(count)+’ occurrences of 13 and ’ +
str(daycount) + ‘entries on Wed’
# answer: 15 occurrences of 13 and 8 entries on Wed
EXAMPLE: CREATING TEXT DATA
Problem:
Your simulation program needs to read in a simple
text file with increasing times listed on each line.
You have a pipe with length 1000 m and an inlet
velocity of 100 m/s. The pipe is divided into 70
sections and you need the particle injection times to
have evenly spaced particles of 4 impulses per section
over the span of 5 seconds.
SOLUTION
per_section = 4
length = 1000
elements_per_length = 70
inlet_velocity = 100
total_time = 5
import math
emission_time = length / elements_per_length / inlet_velocity /
per_section
total_count = int(math.ceil(total_time / emission_time))
print “Continual time emission in seconds: " +
str(emission_time)
f = open("emission_times",'w')
for i in xrange(total_count+1):
f.write(str(round(i*emission_time,3))+"\n")
f.close()