Python Pt1 0702
Python Pt1 0702
Instructor
Peter G. Carswell Supercomputer Resource Specialist Ohio Supercomputer Center [email protected] (614) 292-1091
Python Programming
Table of Contents
Introduction The Not-So-Full Monty Mechanics of using Python Variables, Data Types and Operators Programming statements Python Functions Using Python Modules Everything is an Object Classes and Objects Operator Overloading Constructors
Python Programming
What is Python?
NOT an acronym (Thank goodness!). Named after Monty Python A compiled/interpreted mid-level language
Not only used for scripting tasks
Extremely useful for a huge variety of programming tasks (Modules) Easy to glue with other languages (C, C++, Java ) Under the hood: Object Oriented Commonly in use: Versions 2.3 and 2.4
Use python V to see the version
Python Programming
Basic Operation
Python is both an interpreted and a compiled language When run, the program is first read and compiled in memory
Not a true compilation to native machine instructions Python source code converted to byte code (platform-independent) Some optimizations are performed, e.g.
eliminating unreachable code reducing constant expressions loading library definitions
Second stage is line-by-line execution via the interpreter PVM (Python Virtual Machine)
analogous to Java VM
Much faster than fully interpreted languages, such as the shell No object code
But byte code saved in a file called prog.pyc
Python Programming
Running Python
Python Programming
Python Programming
Notice that only the text directly written out to stdout will appear on your monitor
Python Programming
$ chmod u+x rabbit.py Now the rabbit file looks like this:
#!/usr/local/bin/python print "Hello World! (with respect)" a=34.5 a a*5.6 z=a/33.3 print '%7.2f' %(z)
To run the commands in the rabbit.py file, just type its name at the system prompt
$ rabbit.py Hello World! (with respect) 1.04 Python Programming 9
Python Programming
Variables Pick any name you want as long as it begins with a letter or underscore Dont have to declare the variable name or type Variable comes into existence when it is assigned a value Case-sensitive Actually much more to variable assignments. Fascinating approach when we get to objects .
Python Programming
11
Data Types Python has five built-in, core data types. Listed here in the order in which they will be covered
Python Programming
12
Numbers in Python
Type
Decimal Integers
Examples
10 -235
Octal and Hexadecimal Integers 034723 Long Integers (unlimited size) Floating-Point Complex
0x3DE56A
777888207468890L
3.45
6.2e-15
4E23
6.2+3J
5+8.7j
Python Programming
13
Numerical Operators The table below shows the numeric operators with precedence going from high to low. Due to operator overloading, these symbols can also be used with other types.
Symbol
+x -x x**y x*y x%y x/y x//y
Name
Unary Operators Exponentiation Multiplication, modulus, normal division, truncating division Addition, Subtraction
x + y
x-y
Python Programming
14
Python Programming
15
Python Division
Python 2.2.3 (#1, Oct 26 2004, 17:11:32) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-47)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 7.0/3.0 2.3333333333333335 >>> 7/3 2 >>> 7.0/11.0 0.63636363636363635 >>> 7/11 # Integer division truncates 0 >>> 7%3 # Modulus (remainder) operator 1 >>> 83.56%13.3 # Works for floats too 3.759999999999998 >>> 18//5 3 >>> 18.0//5.0 # Truncating divide for floats as well 3.0 >>> divmod(9,4) # Returns (x/y,x%y) tuple (2,1) $
Python Programming
16
#Truncating Conversion #Can round-up #Octal literals have leading 0 #Hex literals have leading 0x
Python Programming
17
Long integers marked with a trailing L. They can have unlimited size but at the price of poor performance.
>>> x=6666666666444444448882222222990000004444444882119L >>> y=5555999999997777777777222163489390372039309309L >>> x+y 6672222666444442226659999445153489394816484191428L >>> 5**100 7888609052210118054117285652827862296732064351090230047702789306640625L >>>
Python Programming
18
Displaying Floating-Point Numbers A fundamental point of computers: word length used in hardware on a specific machine determines actual precision.
>>> power=2.0**0.3 >>> power 1.2311444133449163
#Echoing of variable results always #returns the real precision. In this #case ~15 decimal places (8 byte word)
>>> print power 1.23114441334 >>> "%e" % power '1.231144e+00' >>> "%1.5f" % power '1.23114' >>>
Python Programming
19
Complex Numbers A feature* of some implementations of complex numbers in python is that the coefficient must be represented in decimal format, i.e. 5.0j not 5j.
*feature is a term used by programmers to make excuses for programs which produce bogus results.
>>> 3.2+5.0J + 6+2.3.0J #Addition (9.1999999999999993+7.2999999999999998j) >>> 3.2+5.0J - 6+2.3j (-2.7999999999999998+7.2999999999999998j) >>> (3.2+5.0j)-(6+2.3j) #Proper Subtraction (-2.7999999999999998+2.7000000000000002j) >>> (3.2+5.0j)*(6+2.3j) # Multiplication (7.700000000000002+37.359999999999999j) >>> (3.2+5.0j)/(6+2.3j) # Division (complex definition) (0.74352143376120128+0.54831678372487291j) >>> z=6.28+7.83j >>> abs(z) # Gives the magnitude 10.037295452461285 >>> z.real # Gives the real part 6.2800000000000002 >>> z.imag # Gives the imaginary part 7.8300000000000001 >>>
Python Programming
20
The Amazing Assignment Operator We have been blithely using = (the assignment operator) to assign variables names to numeric values. It has other interesting properties Multiple assignments: single statement
The statement x = y = z =25 will assign all three variables to 25 Handy shortcut
Python Programming
21
Augmented Assignment
>>> sum=52; >>> sum=sum+36; sum #Normal syntax 88 >>> sum=52; >>> sum += 36; sum #Combined syntax 88 >>> sum *= 10; sum 880 >>> x0=0.0; y0=0.0; z0=0.0; print x0,y0,z0 0.0 0.0 0.0 #Normal syntax >>> x0=y0=z0=13.2; print x0,y0,z0 13.2 13.2 13.2 #Multiple assignment
Python Programming
22
Some key points: Proper perspective: Ordered Collection of Characters No character data type; just one element strings SINGLE and DOUBLE quotes work the same New operand : triple quotes (Block Strings) Strings are immutable sequences Immutable => individual elements cannot be assigned new values Sequence => positional ordering (i.e., indexed) Since strings are character arrays, can use array operations on them Special actions encoded as escape sequences (\n) Raw strings will not recognize escape sequences Strings can be converted to other types and vice versa A collection of built-in string functions (called methods) exist
Python Programming
23
Python Programming
24
Python Programming
25
String Operators
Expression
str1 + str2 str *n str[i] str[i:j] len(str) max(str) min(str) n*str
What Happens
Concatenation Replication (n is an integer) String element with index i Substring of consecutive elements (i to j-1) Number of characters in a string Maximum element (ASCII value) Minimum element (ASCII value)
Python Programming
26
Python Programming
27
Finish theWork
>>> print len(rur) 19 >>> print max(rur) t >>> print min(rur) >>> # Number of elements # ASCII code for t= 116 # ASCII code for (space) = 32
Python Programming
28
Strings playing well with others The addition symbol + is overloaded: it can add two integer operands, two floating point operands, and (as we have just seen) two string operands. And this is just the beginning of the overloading If you try to add a string to an integer directly you have mixed operands and the compiler doesnt know what to do. Same vice versa. Need to use built in type conversion operators
Python Programming
29
Python Programming
30
We have been using the Python print command without giving a proper explanation of its use. This interlude should remedy the situation. print
Takes a list of strings as argument, and sends each to STDOUT in turn Adds a space amid items separated by commas Adds a linefeed at the end of the output. To prevent this, put a comma at the end of the last string in the list Examples:
print Hello,world # prints Hello world with newline print (2+3), foo, # prints 5 foo no newline print ((2+3),bar) # prints tuple (5 bar)
Python Programming
31
Control string
See printf man page for further details >> man printf
Python Programming
32
Interlude: Can we provide input to Python programs? Yes. The most basic of reading commands is called (aptly enough) raw_input() When raw_input() is executed, the program stops and waits for input from stdin (your keyboard) It will read in a line of input IMPORTANT POINTS Prompting and input can be done at the same time. A string argument given to raw_input() will printed to stdout and the function will then wait for input
Clever way of encouraging prompts Prompts are optional, though
Python Programming
33
#!/usr/bin/python year=raw_input("Please enter a year:") year=int(year) #convert input string to int ten=year+10 print "A decade later will be", ten x=raw_input("Enter x coord: ") #prompt along with input x=float(x) #convert input string to float y=raw_input("Enter y coord: ") y=float(y) r=(x**2+y**2)**0.5 print "Distance from origin is", r
Python Programming
34
An Input Session
$ read.py Please enter a year:1963 A decade later will be 1973 Enter x coord: 3.0 Enter y coord: 4.0 Distance from origin is 5.0 $ read.py Please enter a year:2260 A decade later will be 2270 Enter x coord: 13.4 Enter y coord: 56.2 Distance from origin is 57.7754273026
Python Programming
35
More Refined Input There is a close cousin to the raw_input() function called simply input(). It works in the same manner and has all the properties of raw_input() except for one important distinction input() will not read in all input as strings (resulting in possible subsequent conversion). It will read input and give it the appropriate built-in type. Here are some examples of its use:
>>> year=input("Please enter a year: ") Please enter a year: 2001 >>> year 2001 >>> x=year*5; x 10005 >>> money=input("Please enter the amount in your wallet: ") Please enter the amount in your wallet: 13.00 >>> add_Grant=100.00+money; add_Grant 113.0
Python Programming
36
Immutable Strings????
Can you really not change a string after it is created? No, it can be changed. What is not allowed is to change individual elements by assigning them new characters We can use all the string manipulation techniques seen so far to change a string. We can also use the % sign as an operator that allows a string to have any appearance desired (string formatting). The % operator acts like the C function sprintf(). We can also change strings by using a set of special functions associated with strings called methods. String methods is our next section.
Python Programming
37
Changing Strings
>>> cheer="Happy Holidays!"; cheer 'Happy Holidays!' >>> cheer[6]=B #Cannot do Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment >>> cheer[6:11] 'Holid' >>> cheer[6:11]="Birth #Still cannot do Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support slice assignment >>> cheer=cheer[0:6] + "Birthday" + cheer[-1] >>> cheer 'Happy Birthday!
Python Programming
38
String Methods
As was mentioned previously, string methods are special functions designed to work only with strings. To find out what methods there are and how to use them use the Python help command
help(str), help(int), help(float), .. help argument can also be the name of any variable of a certain type
To use a method on a string, the string must first exist The syntax for using the method uses the dot operator (.). The syntax is as follows:
String_name.Method_name(args)
The full story of methods will be presented later
Python Programming
39
The executable python script strmeth.py contains examples of commands that use string methods. Here is its contents:
#!/usr/bin/python hollow='There is the Shadow' song="Me and my Shadow" index=hollow.find('the') print "The starting index of 'the' in '%s' is %d"\ % (hollow,index) index=song.find('a') print "The index of the first '%s' in '%s' is %d"\ % ('a',song,index) hollow=hollow.replace('Shadow','Light') print "A hopeful message: " + hollow name=raw_input("Enter your name: ") name=name.capitalize() print "Hello %s, welcome to the party, pal" % (name) upsong=song.upper() print "Uppercase: " + upsong
Python Programming
40
Running strmeth.py
$ strmeth.py The starting index of 'the' in 'There is the Shadow' is 9 The index of the first 'a' in 'Me and my Shadow' is 3 A hopeful message: There is the Light Enter your name: robson green Hello Robson green, welcome to the party, pal Uppercase: ME AND MY SHADOW $
Python Programming
41
List Data Type Like arrays Ordered collection of data Composed of elements that can be accessed by indexing Can create sublists by specifying an index range (slicing) Unlike arrays Elements can be of different types (heterogeneous) List can grow and shrink during program execution (flexible) You can change individual elements directly (mutable) Nesting allowed: lists of lists, Can be concatenated together Lists have operators, built-in functions, and methods List creation operator [ ] , elements inside separated by commas
Python Programming
42
Python Programming
43
Changing the lengths of Lists A powerful feature of lists is their flexibility: their size can change. At a low level, list lengths can be changed with element/slice reassignment and the use of built-in list operators. At a higher and easier level is the use of length-changing list methods:
append() append argument to end of list extend(list) extend list with values in the list argument insert(index,variable) insert variable contents before index pop() remove and return last list element remove() remove first occurrence of argument
Note that with proper use of list operators/functions/methods, lists can become many interesting containers of data Stack, queue, array(normal), jagged matrix, dequeue, etc.
Python Programming
44
Python Programming
45
Python Programming
46
Python Programming
47
Flexible Matrices Lists of lists allow the creation of matrices. Normal rectangular matrices as well as jagged matrices where the number of column elements can change with row number and vice versa.
>>> morpheus=[[4,8,6,6,4],[0,9,2,6,2],[6,7,7,5]]; morpheus [[4, 8, 6, 6, 4], [0, 9, 2, 6, 2], [6, 7, 7, 5]] >>> morpheus[1][1] #3x5 matrix 9 #Indexed in normal manner (zero-based) >>> triangle=[[2,7,3],[3,4],[6]]; triangle [[2, 7, 3], [3, 4], [6]] #No. of columns change with row >>> triangle[0][0]; triangle[1][0]; triangle[2][0] 2 3 #First element in each of the three rows 6
Python Programming
48
Dictionary Data Type The Perl dictionary data type is unlike any collection of data we have seen so far in two distinct ways:
The dictionary values are unordered. You cannot think of them as having a sequential relationship The manner in which a dictionary value is accessed is via a key paired with it. Not through integer indexing
In other languages, dictionaries are called associative arrays, hashes, maps, etc. Like lists, a dictionary value can be any other Python type (heterogeneous), size can grow and shrink during use (variable length), nesting is allowed, and its key:value pairs can be directly changed (mutable) Because of its unordered nature, sequential operations cannot be performed on a dictionary. Such operation include concatenation and slicing to make sub-dictionaries As implemented in Python, dictionaries are implemented for very fast lookup. Given a key, Python will return its corresponding value as quickly as possible. Internally dictionaries are hash tables and optimized hashing algorithms are used for value retrieval.
Python Programming
49
Replace your own or library searching algorithms Dictionaries can act like structures in C and records in Fortran 90 (but faster) Dictionaries can implement more-sophisticated data structures, as well Can even be used for sparse matrix implementation due to fast retrieval of relatively few non-zero data elements
Most math packages have their own storage formats for sparse matrices
Dictionaries are ideal to use for you own symbol tables, menu selection, etc. Interface to Python Data Base Management software is a dictionary Menu for the GUI Python support is also a dictionary
Python Programming
50
>>> top['pres']='F.D.R.'; {'bio': 'Watson', 'play': gway', 'phil': 'Emerson', 'R.E.M', 'math': 'Gauss', 11
>>> top['bio']='Darwin'; top #Can change a value {'bio': 'Darwin', 'play': 'Shakespeare', 'art': 'Vemeer', 'author': 'Hemmin gway', 'phil': 'Emerson', 'direct': 'Kubrick', 'actor': 'Kidman', 'group': 'R.E.M', 'math': 'Gauss', 'phys': 'Newton', 'pres': 'F.D.R.'} >>> del top['actor']; top; len(top) #can delete a key:value pair {'bio': 'Darwin', 'play': 'Shakespeare', 'art': 'Vemeer', 'author': 'Hemmin gway', 'phil': 'Emerson', 'direct': 'Kubrick', 'group': 'R.E.M', 'math': 'G auss', 'phys': 'Newton', 'pres': 'F.D.R.'} 10
Python Programming
51
Python Programming
52
Python Programming
53
A structure is a very useful data type that contains all the diverse information needed to represent a certain variable. AND all this information (which can be of different types) is stored in memory through one variable name. For example, if you were writing solitaire software you would need some variable to represent a playing card. You could declare a variable down which is a card structure. The card structure would have to an integer member which is the number of the card, and a string member which is its suit We will see that the Python Dictionary type can act very much like the structure type supported in other languages. In the example code that follows we create a dictionary that contains all the information about a student.
Python Programming
54
A student Dictionary
>>> student={name:'Stephen Hawking', #Dictionary definition ... course: 'Astronomy 674', ... ID: 25310157, ... GPA: 4.50, ... Exams: [100,98,99], ... Housing: {'dorm':'McCutcheon','room':137}, ... Final: 95, ... Grade: 'A' } >>> student['GPA'] #Access any student info by member name 4.5 >>> ave=(student['Exams'][0]+student['Exams'][1]+student['Exams'][2])/3.0; ave 99.0 #Working with string:list item >>> student['email']='[email protected]'; student #Add new item {'course': 'Astronomy 674', 'email': '[email protected]', 'Exams': [100 , 98, 99, 105], 'Grade': 'A', 'Housing': {'dorm': 'McCutcheon', 'room': 137 }, 'Final': 95, 'GPA': 4.5, 'ID': 25310157, 'name': 'Stephen Hawking'} >>> student['Housing']['room']=555 #Switched to a new room >>> student['Housing'] #Nested Dictionary {'dorm': 'McCutcheon', 'room': 555}
Python Programming
55
Python Programming
56
Python Programming
57
>>> sts=('Ezek','Guiliani','Woodall','Ennis','Carswell'); >>> sts_list=list(sts); sts_list #Convert tuple to a list ['Ezek', 'Guiliani', 'Woodall', 'Ennis', 'Carswell'] >>> sts_list.append('Carson'); sts_list #Now can append ['Ezek', 'Guiliani', 'Woodall', 'Ennis', 'Carswell', 'Carson'] >>> sts_list.sort(); sts_list #Now alphabetize names ['Carson', 'Carswell', 'Ennis', 'Ezek', 'Guiliani', 'Woodall'] >>> sts=tuple(sts_list); sts #Convert list to tuple ('Carson', 'Carswell', 'Ennis', 'Ezek', 'Guiliani', 'Woodall') >>>
Python Programming
58
Exercise Set 1
1. Write a program that computes the area of a circle of radius 12.5. 2. Modify the above program so that it prompts for and accepts a radius from the user, then prints the area and circumference. Also print out the ratio of the circumference and the diameter to the highest accuracy allowed on your machine. 3. Write a program that reads a string and a number, and prints the string that number of times on separate lines. (Hint: use the x operator.) 4. Write a program that creates a list of lists and prints out the main list in reverse order as well as each element list. 5. Write a program that makes a dictionary of tuples and numbers, and prints the numbers that are selected by two different tuples you pick. (The keys are tuples and the values are numbers).
Python Programming
59
Exercise Set 1
6. Write a program that reads and prints a string and its mapped value according to the dictionary
Input red green blue Output apple leaves ocean
7. Write a program that creates a dictionary of acronyms. The keys are the acronyms and the values are the actual phrases. Make this list as long as you can. When are finished print out all the acronyms and all the actual phrases. 8. An interesting application of complex arithmetic is rotating 2D points about the origin by an angle, theta. Invoke an interactive session in python. Verify the following algorithm:
For a 2D point, in the xy-plane and an angle, theta, in radians, a new coordinate can be calculated by: rot = (x + yj)*(cos(theta) + sin(theta)j) newx = rot.real newy = rot.imag
Python Programming
60
Programming Statements
Python Programming
Truth
Some of the programming constructs discussed in the chapter are controlled by an expression that evaluates to true or false. So, as introduction, we will discuss how Python tests for equality, makes relative comparisons, and even tests for membership in structured variables. In Python, truth and falseness are defined as follows: Numbers are true if nonzero; false otherwise Other variables are true if nonempty; false otherwise How does Python compare variables of built-in types? Numbers are compared by their relative value
Built-in relational operators cannot be used on complex numbers
Strings are compared character-by-character until a pair of different characters are encountered. These characters are then compared by ASCII code (lexicographically) Lists (and tuples) are compared by looking at each member (from left to right) Dictionaries are compared as though comparing sorted (key,value) lists. Note: Python comparison tests continue recursively through nested variables if need be. How does Python test for membership in sequence built-in types? The Boolean operator in is used
Python Programming
62
Meaning Strictly less than Strictly greater than Less than or equal to Greater than or equal to Equal to Not equal to a is an element of Box a is not an element of Box
Python Programming
63
Logical Boolean Operators In the following table, b and d are anything that evaluates to true or false
Operator not b
Meaning
Reverses logical state of b. If b true, not b is false and vice versa True if b and d both true. False otherwise True if b is true, d is true or both are true
b and d b or d
Python Programming
64
Example Code
>>> (0, >>> 0 >>> 1 >>> 3.2 < 1.2, 234 > 12, "Draco" >= 'Draco', 'courts'<='course' 1, 1, 0) #Numbers and strings [1345,'Pyrite',4.56] >= [1345,'Pyrite',4.562] #Lists [22,['one','too','throw']] <= [22,['one','two','three']] #Nested Lists {'E':90,'W':270,'N':0,'S':180} == {'N':0,'E':90,'S':180,'W':270} 1 #Dictionaries >>> ('N',0) >= ('N',360) 0 #Tuples >>> 'on' in [22,['one','too','throw']] #Membership 0 >>> 'one' in [22,['one','too','throw']] 0 >>> 'one' in [22,'one',['too','throw']] 1 >>> ['too','throw'] not in [22,'one',['too','throw']] 0
Python Programming
65
>>> >>> >>> >>> 1 >>> 1 >>> >>> 0 >>> >>> 1 >>>
lower=16 upper=88 x=33 x>lower and x<upper lower < x < upper x=5 lower < x < upper x=16 lower <= x <= upper
Python Programming
66
Python if/else Statement Basic decision-making statement: choose between executing two different blocks of code using the output of a controlling Boolean expression. Syntax is
if <Boolean expression>: <statement block1> else: <statement block2>
Synatx Properties NO begin/end or braces to mark blocks of code. Code blocks detected automatically All Python code blocks follow same template. A header line with a colon at the end, followed by statements all indented by the same amount. (You pick the amount of indentation) if statement header must begin in column 1 If using if interactively need a blank line at the end for it to execute
Python Programming
67
Python Programming
68
Python Programming
69
Multiple Choices
Python does not have the equivalent of a switch or case statement which allow one of many code blocks to be executed. The if/else statement can be extended with elif clauses to perform this task and create even more sophisticated decision making code blocks.
Python Programming
70
An elif Ladder
$ cat author.py #!/usr/bin/python writer=raw_input('Please enter the name of an author: ') if writer=='Melville': print 'Moby is a direct descendent' elif writer=='Fleming': print 'Into James Bond 007' elif writer=='Irving': print 'Garp, Garp, Garp!' elif writer=='Dickens': print 'God Bless us everyone' elif writer=='Faulkner': print "The Past isn't dead." print "It's not even past." else: print "Haven't heard of that writer"
Python Programming
71
In Use
$ author.py Please enter the name of an author: God Bless us everyone $ author.py Please enter the name of an author: The Past isn't dead. It's not even past. $ author.py Please enter the name of an author: Moby is a direct descendent $ author.py Please enter the name of an author: Haven't heard of that writer $
Dickens
Faulkner
Melville
Steele
Python Programming
72
where the <entry condition> is the controlling Boolean expression. Operation: While the entry condition is true the loop body is executed repeatedly. When the entry condition is false the (optional) else statement block is executed and the loop is exited Comments:
If entry condition is never true, loop body will never be entered and executed In this form of the while loop, some code must cause the entry condition to go false or else the dreaded
Python Programming
73
$ cat stumble.py #!/usr/bin/python dist=0; steps=0; while (abs(dist) != 3): #Entry Condition entry=raw_input('Flip a coin. Enter h or t: ') if (entry=='h'): dist += 1 steps += 1 elif (entry=='t'): dist -= 1 steps += 1 #End of Loop Body print 'You took %d steps' % steps $
Python Programming
74
Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter Flip a coin. Enter You took 9 steps
h h h h h h h h h
or or or or or or or or or
t: t: t: t: t: t: t: t: t:
h t t h t h t t t
Python Programming
75
Operation: During each iteration the loop variable is assigned elements from the sequence (in-order) and the loop body is executed. Normally, the looping ends when the last element in the sequence has been reached. Notes: After the for loop is finished, the loop variable has its last value else clause works the same way as it does in the while loop and is optional
Python Programming
76
Python Programming
77
Python Programming
78
range Function A common reaction to the first example for loop shown is You mean I have to type out ALL the integers I want the loop counter to get?????? Since this would be antiquated and barbaric, Python provides a solution to the problem with the range function. The range function returns a list of integers starting with the first argument and ending before the second Range(1,5) => [1,2,3,4] argument.
Range(4) => [0,1,2,3] #Default start at 0 Range(0:16:3) =>[0,3,6,9,12,15] #Can choose stride
So
>>> for num in range(1,6): ... num=num**2 ... print num, our offending for loop becomes: ... 1 4 9 16 25
Python Programming
79
There may be times when you wish to leave a for loop before the last item or a while loop before the entry condition becomes false. This is accomplished with the use of the Python break statement. When a break is encountered control will jump out of the enclosing loop and move on to new code Related to the break statement is the continue statement. If a continue is encountered the rest of loop body for that iteration is skipped over. Then the next iteration starts at the beginning of the loop. For no good reason, we will also mention the pass statement. It is Pythons equivalent to a no-op. It does nothing at all.
Python Programming
80
Heres how
>>> pairs=[(3,4),(-5,2),(2.37,0.01),(6,0),(45.6,89.2)] >>> for (num,den) in pairs: ... if den != 0: ... print (num/den), ... else: ... continue #Stop division by zero ... ... 0 -3 237.0 0.511210762332 >>> all='' >>> while 1: ... lett=raw_input('Enter a letter (5 to stop): ') ... if lett=='5': break #How to stop inputting ... all=all+lett ... Enter a letter (5 to stop): r Enter a letter (5 to stop): I Enter a letter (5 to stop): e Enter a letter (5 to stop): 5 >>> print 'Your letters were '+all Your letters were rIe
Python Programming
81
Exercise Set 2
1. Write a program that accepts the name and age of the user and prints something like Bob is 26 years old. Insure that if the age is 1, year is not plural. Also, an error should result if a negative age is specified. 2. Write a program that reads a list of numbers on separate lines until 999 is read, and then prints the sum of the entered numbers (not counting the 999). Thus if you enter 1, 2, 3 and 999 the program should print 6. 3. Write a program that reads a list of strings and prints out the list in reverse order, but without using the reverse operator. 4. Write a program that prints a table of numbers and their cubes from 0 to 32. Try to find a way where you dont need all the numbers from 0 to 32 in a list, then try one where you do. 5. Build a program that computes the intersection of two arrays. The intersection should be stored in a third array. For example, if a = [1, 2, 3, 4] and b = [3, 2, 5], then inter = [2, 3].
Python Programming
82
Exercise Set 2
6. Write a program that generates the first 50 prime numbers. (Hint: start with a short list of known primes, say 2 and 3. Then check if 4 is divisible by any of these numbers. It is, so you now go on to 5. It isnt, so push it onto the list of primes and continue) 7. Build a program that displays a simple menu. Each of the items can be specified either by their number or by the first letter of the selection (e.g., P for Print, E for Exit, etc.). Have the code simply print the choice selected. 8. Write a program that asks for the temperature outside and prints too hot if the temperature is above 75, too cold if it is below 68, and just right if it between 68 and 75. 9. Write a program that acts like cat but reverses the order of the lines.
Python Programming
83
Python Functions
Python Programming
Python Programming
85
Function Definition
Defining a function means writing the actual Python code that causes the function to do what it does. This, of course, is the syntax for a function definition:
def <function_name>(arg1,arg2,): <block statement> return <value>
The first line of this definition is often called the function header. The statements making up the function are often called the function body. Operation: When a call to the function is made, actual arguments in the call will be matched up with dummy arguments here in the definition. The function body will be executed. The return statement ends the function call and passes back the return value Comments:
There can be zero dummy arguments The return statement is not required if the function does not return any data The connection between an actual argument and a dummy argument is through assignment. That is, the value of the actual argument is assigned to the dummy argument during function execution
Python Programming
86
Simplicity itself. Just type the function name followed by a list of actual arguments in parentheses. Even if there are no arguments, the parentheses are still required. Here are some sample function calls:
perimeter=rectangle(4.3,8.2) print_description() vowel_list=decompose(word)
Python Programming
87
Python Programming
88
In the sample program just shown, you could see that scale_sum worked for integer arguments, floating-point arguments, and even strings! This is an integral part of Python function design: the arguments are not typed. Any type variable that can be added and multiplied can be used in scale_sum This is an example of a broader concept called Polymorphism: the meaning of code depends upon the types of the variables being used. Having a function (with the same name) work with different actual argument types is supported in other languages by generic functions, and template functions.
Python Programming
89
#!/usr/bin/python x=6 print 'outside x before call: ',x def gsum(y,z): global x x=y+z; return x back=gsum(22,8) print "Global sum= ",back print 'outside x after call: ',x def lsum(y,z): x=y+z; return x back=lsum(4,8) print "Local sum= ",back a=33 print 'outside a before call: ',a def nsum(y,z): a=y+z; return a back=nsum(5,6) print "No sum= ",back print 'outside a after call: ',a
Python Programming
90
Program Results
outside x before call: 6 Global sum= 30 outside x after call: 30 Local sum= 12
Python Programming
91
Two concepts to learn: If the actual argument is of an immutable data type, changing the matching dummy argument does not change the actual argument. If the actual argument is of a mutable data type, changing the matching dummy argument does change the actual argument.
Python Programming
92
Python Programming
93
Code Results
String before function call: adamantium function returned helium String after function call: adamantium List before function call: [2, 635.8, 'eight', 44, 12.34] function returned [2, 635.8, 8, 44, 12.34] List after function call: [2, 635.8, 8, 44, 12.34]
Python Programming
94
Python functions have two very nice features that are just now appearing in user-defined functions. Dummy argument names can act as keywords. In the call to a function the actual argument can specify BY KEYWORD name which dummy argument it is matched with.
Overrides the traditional matching be position Self-documents code if you pick meaningful keywords When one actual arg using a keyword, all remaining actual args must as well
The second feature is that dummy arguments can be given a DEFAULT value. If no actual argument ends up being matched to that dummy argument it is assigned its default value
Handy for arguments that rarely change with each call to the function. The functional call can have less actual arguments in it.
Python Programming
95
Python Programming
96
25.0 acc= 1e-07 18.0 acc= 0.001 500.0 acc= 0.001 500.0 acc= 0.001
Python Programming
97
Every time a new programming language is taught, this question is always asked at one point. For Python, the answer is YES Python functions can return tuples. Those return values can be assigned to lists. So there is really no limit to the number of values a single Python function can return. CAUTION: Be sure the number of elements in the return tuple equal the number of elements in the receiving list
Python Programming
98
$ cat multiout.py #!/usr/bin/python def more(s1,s2,s3='sil'): S=[s1+s2,s2+s3] L=[len(s1+s2),len(s1+s2)] return(S,L) Merge,Length=more('pro','ton') print "Merge list= ",Merge print "Length list=",Length
Python Programming
99
Exercise Set 3
1. Write a program that accepts a list of words on STDIN and searches for a line containing all five vowels (a, e, i, o, and u). 2. Modify the above program so that the five vowels have to be in order. 3. Write a program that looks through the file /etc/passwd on STDIN, and prints out the real name and login name of each user. 4. Write a function that takes a numeric value from 1 to 9 and returns its English name (i.e., one, two ). If the input is out of range, return the original value as the name instead. 5. Taking the subroutine from the previous exercise, write a program to take two numbers and add them together, printing the result as Two plus three equals five. (Dont forget to capitalize the first letter!)
Python Programming
100
Exercise Set 3
6. Create a function that computes factorials. (The factorial of 5 is 5! = 5*4*3*2*1 = 120.) 7. Build a function that takes an integer and returns a string that contains the integer displayed with a comma every three digits (i.e., 1234567 should return 1,234,567). 8. Write a function that numerically sorts a list of integers. The list elements should NOT be sorted by ASCII value as is done by the built-in sort 9. Write a function called mergedict(dict1,dict2) that determines the merger of two dictionaries. It should return a new dictionary with all the items in both of its arguments. If the same key is used in both dictionary print an appropriate error message and leave those items out of the merger.
Python Programming
101
Python Modules
Python Programming
Module Properties DEFN: A file of Python code (suffix .py) which can contain variable assignments, function definitions, and type definitions typically all relating to a specific topic In Python modules take the role of libraries. The code in them can be used and reused by different Python programs.
Almost identical definition, use and philosophy of Fortran 90 modules
The use of the attributes of module (the names in them) is accomplished by simply importing the module. Naturally enough, this is done with the Python command import. There are three general categories of modules available to the Python programmer:
Modules that were provided with the Python installation Modules downloadable from the web Modules you can write yourself!
Python Programming
103
Python Programming
104
Some Observations As shown in the previous demo program an extremely helpful Python function is dir. When applied to a module it list all the names that are contained in the module. Most of the names will be functions, some will be values. Not that the same dot notation described previously for member functions also works with identifying a value. Thus, to use pi we typed the code math.pi It should be pointed out that importing a Python module is not the simple text insertion that occurs when files are included as in other languages. The import command actually involves three separate steps: finding required module files, compiling the module to bytecode, and running any executable statements that are in the module source code. Lastly, you probably noticed that some module attributes that begin and end with two underscores. These are special methods that are part of the operation of all modules, so their names are chosen for us. Some have to do with system interfacing, others with containing information about the complete module, operator overloading, etc.
Python Programming
105
www.python.org
Python Programming
106
>>> Ships=['Redstone 7','Saturn 5','Arriane','Soyuz','Space Shuttle', ... 'Proteus','Ranger','Delta II'] >>> Ships.sort() >>> Ships ['Arriane', 'Delta II', 'Proteus', 'Ranger', 'Redstone 7', 'Saturn 5', 'Soyuz', 'Space Shuttle'] >>> from bisect import bisect_left #from allows method to be #used without module. prefix >>> where=bisect_left(Ships,'Skylab'); where 6 #Index where new element would go in list >>> from bisect import * #import all methods >>> insort_left(Ships,'Skylab'); Ships #Put new element in #correct spot ['Arriane', 'Delta II', 'Proteus', 'Ranger', 'Redstone 7', 'Saturn 5', 'Skylab', 'Soyuz', 'Space Shuttle'] >>> insort_right(Ships,'Nike',2,6); Ships #Can specify List range ['Arriane', 'Delta II', 'Nike', 'Proteus', 'Ranger', 'Redstone 7', 'Saturn5', 'Skylab', 'Soyuz', 'Space Shuttle']
Python Programming
107
Writing your own Modules Here is a demo module dealing with complex numbers written by the author.
$ cat modern.py print "Beginning import" C=3.0+4.0j #Module variable(global to importer)
def partner(c): res=complex(c.real,-c.imag) #Module method return(res) def peri(c): #Another Module method res=0.0 res=abs(c.real)+abs(c.imag)+abs(c) return(res) print "Import ended"
Python Programming
108
>>> import modern Beginning import #import Runs executable statements Import ended >>> dir(modern) #Yes, works on your own modules ['C', '__builtins__', '__doc__', '__file__', '__name__', 'partner', 'peri'] >>> modern.C (3+4j) >>> modern.partner(modern.C) (3-4j) >>> d=24-13j >>> modern.peri(d) #modern Methods can take any arg 64.294688127912366 >>>
Python Programming
109
Python Programming
YOU CAN WRITE YOUR OWN OOP CODE: Class definitions, Object creation, methods, operator overloading, etc
Python Programming 111
Dynamic Typing Dynamic typing is the actual means by with Python has been creating objects As you have seen from the start, Python variables names are not declared by you to have a certain type. Variable types are determined while the program is running (thus dynamic) with the use of the assignment statement = Consider this simple Python statement: alex=[0,2,4,6,8] which we know gives a list of even numbers to the name alex. The following is what Python does when it encounters the assignment statement:
Create a list object in memory to hold [0,2,4,6,8] Create the variable alex Link the name alex to the new object [0,2,4,6,8]
When the name alex appears in Python code is is replaced with the list object it is linked to. The links from variable names to objects are officially called references. References are very similar to C pointers which contain memory addresses. (But note that Python references are automatically dereferenced when used. Sweet)
Python Programming 112
Python Programming
Class Syntax
The first step in your own Python OOP is define the new type you desire through a class definition The syntax of Python classes is:
Python Programming
114
Class Rectangle
$ cat Figures.py class Rectangle: def setheight(self,value): self.height=value def setwidth(self,value): self.width=value def area(self): self.area=self.height*self.width def display(self): print "Height:",self.height,"Width:",self.width
Python Programming
115
Python Programming
116
Operator Overloading
Python Programming
What is Operator Overloading? An operator is overloaded when it has been designed to work with more than one type of operands. For example, the addition operator will correctly work with with all the built-in number types and with the string type. Python has been written this way. In most languages, operators are already overloaded by handling its own built-in data types What OOP allows a programmer to do is overload operators so that they work with objects of their own new data types. Python makes this particularly straightforward by having names reserved just for operator overloading of specific operators. For example, the method name __len__ should be used to overload the len operator. The programmer must write the code body for a function of this name. When overloading an operator, it is considered good form to make what the operator does with your objects be similar to what the operator traditionally does. In the following slides, we revisit our Rectangle class and decide what is means to add together two Rectangle objects.
Python Programming
118
Python Programming
119
Python Programming
120
Initialization
Recall that in the first form of the Rectangle class that objects dataheight and width- were given values by set functions. After a while, it gets irritating to call a number of set methods. What is desired is a method to initialize an object,s data at declaration, just like with any built-in object. The initialization object method is called a Constructor and a name has been set aside for it: __init(self,)___ In the new Rectangle class, you can see that a constructor has been written to give any Rectangle object starting values for height and width. Notice that its arguments can even have default values
Python Programming
121