You are on page 1of 121

Python Programming

Science & Technology Support Group
20-21 February 2007

Peter G. Carswell Supercomputer Resource Specialist Ohio Supercomputer Center (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 is portable Python is free! Home Page:

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

To use Python: Interactive
• Type python in a shell window and start typing in commands at the Python prompt >>>. The results of the commands will be seen immediately.
[piv-login1]% python Python 2.2.3 (#1, Feb 2 2005, 12:20:51) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> print "Hello World! (with respect)“ #Basic output command Hello World! (with respect) >>> a=34.5 # No variable type declaration >>> a # To see contents of variable, type its name 34.5 >>> a*5.6 193.2 >>> z=a/33.3 >>> print '%7.2f' %(z) #Formatting Output 1.04 >>> ^D #How to exit the Python session $

Workshop examples will be for Python on Unix/Linux system.

Python Programming


Ways to use Python: Shell Scripts
• A shell script is just a series of python commands entered line-by-line into a file. By typing the name of the shell script after the python executable, all the commands will be run in order. By convention files composed of Python commands have the suffix py. Let’s say all the commands on the previous slide have been put into a file Here’s how it would be run:
$ python Hello World! (with respect) 1.04 $

Notice that only the text directly written out to stdout will appear on your monitor

Python Programming


Ways to use Python: Executable Scripts
• Say you want to run your Python script directly at the system prompt. (Just like an operating system command). This requires two steps
– Make the first line in the file

#!<full pathname of Python executable>
– Second, give executable permission

$ chmod u+x • 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 file, just type its name at the system prompt
$ Hello World! (with respect) 1.04 Python Programming 9

Variables, Data Types and Operators

Python Programming

Variables • • • • • Pick any name you want as long as it begins with a letter or underscore Don’t 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


Data Types • Python has five built-in, core data types. Listed here in the order in which they will be covered

Numbers Strings Lists Dictionaries Tuples

Python Programming


Numbers in Python

Decimal Integers

10 -235

Octal and Hexadecimal Integers 034723 Long Integers (unlimited size) Floating-Point Complex








Python Programming


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.

+x -x x**y x*y x%y x/y x//y

Unary Operators Exponentiation Multiplication, modulus, normal division, truncating division Addition, Subtraction

x + y


Python Programming


Operator Precedence & Parenthetical Override
$ python 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. >>> a=40 >>> b=3 >>> c=75 >>> a*b+c 195 >>> a*(b+c) 3120 >>> $

Python Programming


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


Alternative Integer Bases
>>> num=4578 >>> int(num) 4578 >>> int(67.345) 67 >>> round(67.899) 68.0 >>> oct(num) '010742' >>> hex(num) '0x11e2' >>>

#Truncating Conversion #Can “round-up” #Octal literals have leading 0 #Hex literals have leading 0x

Python Programming


Python Long Integers

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


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


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


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

Combined assignment and operation
– The statement x = x + 2.34 can be replaced with x+=2..34 (Taken form C) – The <operator>= syntax can be used for all the numerical operators discussed in this section (and more) – Again, less typing involved (always nice) but more advantages – Only need to evaluate LHS (variable name) once, not twice. We will see later that some Python variables can are quite large – This shortened syntax will cause the compiler to automatically pick the optimized technique for performing the combined operations. This advantage will have a greater effect on the more sophisticated data types to come.

Note for C/C++ users: no increment/ decrement operators (++,--) in Python

Python Programming


“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


String Data Type

• 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


Making Strings (I)
>>> s='Galaxy Formation Era'; print s # Single Quote Galaxy Formation Era >>> d="Star Formation Era"; print d # Double Quote Star Formation Era >>> maybe="liberty, equality, fraternity‘ # Mixing? File "<stdin>", line 1 maybe="liberty, equality, fraternity' ^ SyntaxError: invalid token >>> meryl="Sophie's Choice"; print meryl # Quote in string Sophie's Choice3 >>> streep='Sophie"s Choice'; print streep #Quote in string Sophie"s Choice >>> phrase="Shoot out" 'the lights'; print phrase #Concatenation Shoot outthe lights >>> empty="Shoot out" '' "the lights"; print empty Shoot outthe lights >>> spaced="Shoot out" ' ' "the lights"; print spaced Shoot out the lights >>>

Python Programming


Making String (II)
>>> totab="Dalton\tEnnis"; print totab #Escape Character Dalton Ennis >>> ornottotab=r"Dalton\tEnnis"; print ornottotab #Raw String Dalton\tEnnis >>> absolute=R"D:\Matlab\Neural Networks"; print absolute D:\Matlab\Neural Networks >>> alum="""The Truth # Triple Quote ... shall set ... you free""" >>> print alum The Truth shall set you free >>> linear='The Truth \ # Using more than one line ... shall set \ ... you free' >>> print linear The Truth shall set you free >>>

Python Programming


String Operators

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


Working with Strings
>>> one="Vaya "; two='con '; three="Dios" >>> goodbye=one+two+three; print goodbye # + is concatenation Vaya con Dios >>> byrds='Turn ' >>> lyric=byrds * 3; print lyric # * is replication Turn Turn Turn >>> rur="Protocal Droid C3P0" >>> print rur[5] # String Element (zero-based index) c >>> print rur[9:13] # Substrings Droi >>> print rur[:9] Protocal >>> print rur[9:] Droid C3P0 >>> print rur[:] Protocal Droid C3P0 >>> print rur[-3] # Negative index => relative to end 3 # of string [ length(rur)+i ] >>> print rur[-11:-4] Droid

Python Programming


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


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 doesn’t know what to do. Same vice versa. Need to use built in type conversion operators

• •

Python Programming


Basic String Conversion
>>> lic="APN" + 9253 # DANGER:Mixing operand types Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects >>> lic="APN" + str(9253); lic #int-to-string 'APN9253' >>> limit="55" >>> speeding=int(limit)+20; speeding #string-to-int 75 >>> braking=speeding-30; braking 45 >>> h=6.63E-34 #float-to-string >>> defn="Planck's constant-> "+str(h); defn "Planck's constant-> 6.63e-34" >>> hstring=defn[len(defn)-8:]; hstring '6.63e-34' >>> nu=101E6 >>> energy=float(hstring)*nu; energy #string-to-float 6.6962999999999995e-26 >>>

Python Programming


Interlude: Printing to the Standard Output

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


Printing Formatted Strings
• For formatted output, use print control_string % (variable_list)
– – – – – – Works just like the C function printf The control_string has the text you want outputted along with format_identifiers. A format_identifier begins with the % sign, has optional numbers, and ends with a letter code standing for the type of variable to be printed out. For example %d stands for a decimal number, %f stands for a floating point number, %s stands for a string, etc. As the print function moves from left to right, when it encounters a format_identifier it substitutes in the corresponding value of the variable from the variable_list. Example:

print ”Out %15s %5d %10.2f\n” % (a,b,c)

Control string
– See printf man page for further details >> man printf

List of items to be printed

Python Programming


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

All input entered will be treated as a string by your Python program.
Must use the conversion commands on the previous slide for other types

Python Programming


The Script

#!/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


An Input Session

$ 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 $ 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


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


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


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


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:

• The full story of methods will be presented later

Python Programming


Using String Methods

The executable python script 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



$ 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


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


Basic List Operations
>>> mix=[3,'tree',5.678,[8,4,2]]; mix #List creation [3, 'tree', 5.6779999999999999, [8, 4, 2]] >>> mix[1] #Indexing individual elements 'tree' >>> mix[0] 3 >>> mix[-2] #Indexing from the right 5.6779999999999999 >>> mix[3] [8, 4, 2] >>> mix[3][1] #Last element is itself a list 4 >>> mix[0]=666; mix #Mutable [666, 'tree', 5.6779999999999999, [8, 4, 2]] >>> submix=mix[0:3]; submix #Creating sublist [666, 'tree', 5.6779999999999999] >>> switch=mix[3]+submix; switch #+ Operator [8, 4, 2, 666, 'tree', 5.6779999999999999] >>> len(switch) #Built-in Funciton 6

Python Programming


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


Lists growing and shrinking (basic techniques)
>>> resize=[6.45,'SOFIA',3,8.2E6,15,14]; len(resize) 6 >>> resize[1:4]=[55]; resize; len(resize) #Shrink a sublist [6.4500000000000002, 55, 15, 14] 4 >>> resize[3]=['all','for','one']; resize; len(resize) [6.4500000000000002, 55, 15, ['all', 'for', 'one']] 4 >>> resize[4]=2.87 #Cannot append this way IndexError: list assignment index out of range >>> temp=resize[:3] >>> resize=temp+resize[3]; resize; len(resize) #add to list [6.4500000000000002, 55, 15, 'all', 'for', 'one'] 6 >>> del resize[3]; resize; len(resize) #delete an element [6.4500000000000002, 55, 15, 'for', 'one'] 5 >>> del resize[1:3]; resize; len(resize) #delete a sublist [6.4500000000000002, 'for', 'one'] 3

Python Programming


Lists growing and shrinking (using methods)
>>> Endless=['Dream',6.2, 140, "Dreamscape",‘black hair']; >>> len(Endless) 5 >>> Endless.remove('Dreamscape'); Endless; len(Endless) ['Dream', 6.20, 140, ‘black hair'] 4 >>> oldtop=Endless.pop(); oldtop; Endless; len(Endless) ‘black hair' ['Dream', 6.20, 140] 3 >>> Endless.append(‘black eyes'); Endless; len(Endless) ['Dream', 6.20, 140, ‘black eyes'] #Acts like a push 4 >>> Endless.insert(1,1E6); Endless; len(Endless) ['Dream', 1000000.0, 6.20, 140, ‘black eyes'] #Before index 5 >>> Endless.extend(['Sister: Death’,7]); Endless; len(Endless) ['Dream', 1000000.0, 6.200, 140, ‘black eyes','Sister: Death’,7] 7

Python Programming


More List Methods
>>> other=[1,'one',9.87,2,'Two',6.54,3,'three',3.21]; >>> other.reverse(); other [3.21, 'three', 3, 6.54, 'Two', 2, 9.8699999999999992, 'one', 1] >>> other.sort(); other [1, 2, 3, 3.21, 6.54, 9.8699999999999992, 'Two', 'one', 'three'] #Ascending order by ASCII code >>> nums=[3,7,9,4,3,7,6,1,2,9,0,3,4,5,6,2,8,9]; >>> nums.count(3) 3 >>> nums.count(7) #How many sevens? 2 >>> nums.count(0) 1 >>> nums.index(6) 6 >>> nums.index(9) #Where is the first nine? 2 >>> nums.index(3) 0 >>> nums.index(5) 13

Python Programming


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


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


Common Dictionary Uses

• • • •

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


Using Basic Dictionary Operands
>>> ... ... >>> 10 top={'math':'Gauss','phys':'Newton','art':'Vemeer','phil':'Emerson', 'play':'Shakespeare','actor':'Kidman','direct':'Kubrick', 'author':'Hemmingway','bio':'Watson','group':'R.E.M'} len(top) #{ } are dictionary creation operators # Syntax {key:value, key:value, …} top; len(top) #Can add a new pair 'Shakespeare', 'art': 'Vemeer', 'author': 'Hemmin 'direct': 'Kubrick', 'actor': 'Kidman', 'group': 'phys': 'Newton', 'pres': 'F.D.R.'} #len operator works for dictionaries

>>> 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


Methods for Dictionary Information
>>> ages=[50,80,-0.6]; >>> names=['kris','budd','robby']; >>> birth={ages[0]:names[0],ages[1]:names[1],ages[2]:names[2]} >>> birth {80: 'budd', 50: 'kris', -0.6: 'robby'} >>> birth.items() #List the pairs [(80, 'budd'), (50, 'kris'), (-0.6, 'robby')] >>> birth.keys() #List the keys alone [80, 50, -0.6] >>> birth.values() #List the values alone ['budd', 'kris', 'robby']

Python Programming


Methods for Working with Dictionaries
>>> birth.get(50) #Get the value paired with key argument 'kris' >>> birth.popitem() #Remove some item from the dictionary (80, 'budd') >>> birth.popitem() (50, 'kris') >>> birth {-0.6: 'robby'} >>> more={17:'mike',3:'harry',7:'maddy'}; >>> birth.update(more); birth #Add more items to existing dict. {17: 'mike', 3: 'harry', -0.6: 'robby', 7: 'maddy'} >>> years=birth.copy(); years #Make a copy of a dictionary {17: 'mike', 3: 'harry', -0.6: 'robby', 7: 'maddy'} >>> birth.clear(); birth #Clear out a dictionary {} >>> years {17: 'mike', 3: 'harry', -0.6: 'robby', 7: 'maddy'}

Python Programming


Python Dictionaries as C structures

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


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']=''; student #Add new item {'course': 'Astronomy 674', 'email': '', '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


Tuple Data Type
• Type name is historical. The (x,y) positions of a pixel in an image can be referred to as a 2-tuple. The coordinates of a point in space, a 3-tuple. Tuples collect a small number of related objects. Characteristics of the Python Tuple type: – Ordered collection of any type of data ; nestable as well (heterogeneous) – Elements of a tuple are indexed. Subtuples can be created via slicing – Cannot be changed by element reassignment directly (immutable) – Operators we’ve seen before work on tuples, but tuples have NO METHODS Reason for immutability (strings and tuples) is the most obvious one: you don’t want variable’s contents to be accidentally overwritten. Same rationale for declaring a symbolic name to be a constant. Immutability is the major difference between a tuple and a list

Python Programming


Using Tuple Operators
>>> beatles=('Lennon','McCartney','Starr','Harrison','Martin'); #Parentheses () create tuples >>> copyright=beatles[0]+' and ' +beatles[1]; copyright 'Lennon and McCartney‘ #Addition operator >>> extra=beatles[2][len(beatles[2])-1]; extra 'r‘ #Two-level indices; len operator >>> fab_four=beatles[0:4]; fab_four ('Lennon', 'McCartney', 'Starr', 'Harrison') #Range of indices >>> drum_band=beatles[2]*4; drum_band #Multiplication operator 'StarrStarrStarrStarr' >>>

Python Programming


Finessing List Methods

>>> 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


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


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


Programming Statements

Python Programming

• 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


Relational Boolean Operators

Operator Symbol < > <= >= == != a in Box a not in Box

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


Logical Boolean Operators • In the following table, b and d are anything that evaluates to true or false

Operator not b

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

For logical operators and and or, short-cutting is performed

Python Programming


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


FINALLY, syntax appealing Range Checking

>>> >>> >>> >>> 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

#Traditional syntax #Yes, this is legal now

Python Programming


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


Demo if/else Code
>>> now=2005; birth=1952 >>> if (now-birth) >= 21: #Header with colon ... print 'You are of drinking age‘ #Indented lines ... else: ... print 'You are only %d years old' % (now-birth) ... print 'Come back when you are older' ... You are of drinking age >>> birth=1993 >>> if (now-birth) >=21: ... print 'You are of drinking age' ... else: ... print 'You are only %d years old' % (now-birth) ... print 'Come back when you are older' ... You are only 12 years old Come back when you are older >>> if (now-brith) >=21: #Must start in column 1 if (now-brith) >=21: ^ SyntaxError: invalid syntax

Python Programming


Putting if/else in a Python Script
$ cat #!/usr/bin/python now=2005 birth=raw_input('Please enter your birth year: ') birth=int(birth) if (now-birth) >= 21: print 'You are of drinking age' else: print 'You are only %d years old' % (now-birth) print 'Come back when you are older' print 'End of carding‘ #No blank line needed $ Please enter your birth year: 1990 You are only 15 years old Come back when you are older End of carding

Python Programming


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


An elif Ladder …

$ cat #!/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


… In Use
$ Please enter the name of an author: God Bless us everyone $ Please enter the name of an author: The Past isn't dead. It's not even past. $ Please enter the name of an author: Moby is a direct descendent $ Please enter the name of an author: Haven't heard of that writer $





Python Programming


The while Loop

Python’s conditional loop. General syntax is:
while <entry condition> : <statement block1> else: <statement block2>

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 ∞

Loop will raise its ugly head

Python Programming


Random Walk while Loop

$ cat #!/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


Take a walk on the Random side

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


The for Loop
• Python work-horse unconditional loop: it can iterate through items in strings, lists, and tuples. Syntax:
for <loop variable> in <ordered sequence>: <block statement1> else: <block statement2>

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


Some for Loops
>>> for num in [1,2,3,4,5]: #Normal integer loop variable ... num=num**2 ... print num, #Suppress automatic carriage return ... 1 4 9 16 25 >>> sides=[(3.2,6.78),(158,34),('Green',' Day')] #Tuple List >>> for (x,y) in sides: ... print x+y ... 9.98 192 Green Day >>> Dates={1944:'D-Day',1211:'Black Plague',1066:'Norman Invasion', ... 2005:'Bethe Death'} >>> for year in Dates.keys(): #Dictionary Looping ... print Dates[year]+' happened in '+str(year) ... D-Day happened in 1944 Black Plague happened in 1211 Bethe Death happened in 2005 Norman Invasion happened in 1066

Python Programming


Some more for Loops
>>> for c in 'Easter 1911': #String Loop ... if c.isalpha(): ... print '%s is a letter' % c ... elif c.isdigit(): ... print '%s is a number' % c ... elif c.isspace(): ... print '%s is white space' % c ... E is a letter a is a letter s is a letter t is a letter e is a letter r is a letter is white space 1 is a number 9 is a number 1 is a number 1 is a number

Python Programming


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


>>> for num in range(1,6): ... num=num**2 ... print num, our offending for loop becomes: ... 1 4 9 16 25

Python Programming


“How can I get out of this rut?”

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 Python’s equivalent to a “no-op”. It does nothing at all.

Python Programming


Here’s 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


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 don’t 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


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 isn’t, 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


Python Functions

Python Programming

Reasons for Functional Programming

There are many good reasons to program with functions:
– Don’t have to repeat the same block of code many times in your code. Make that code block a function and reference it when needed. – Function portability: useful functions can be used in a number of programs. – Supports the top-down technique for devising a program algorithm. Make an outline and hierarchy of the steps needed to solve your problem and create a function for each step. – Easy to debug. Get one function working correctly then move on to the others. – Easy to modify and expand. Just add more functions to extend program capability – For a large programming project, a specific programmer will code only a small fraction of the program. – Makes program self-documenting and readable.

Python Programming


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

dummy arg = actual arg

Python Programming


Calling a Python Function

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)

Functions must be defined before they are called

Python Programming


Simple Function Use
$ cat #!/usr/bin/python def scale_sum(x,y,z,factor): #Function Definition sum=x+y+z #Local variable res=factor*sum #Return value in local variable return res out=scale_sum(4,2,9,5) #Call with ints print "scale_sum returned",out out=scale_sum(45.2,873.2,5.62,-0.01) #Call with floats print "scale_sum returned",out out=scale_sum('Hip ','Hip ','Horray ',3) #Call with strings print "scale_sum returned",out $ scale_sum returned 75 scale_sum returned -9.2402 scale_sum returned Hip Hip Horray Hip Hip Horray Hip Hip Horray $

Python Programming


Python Function are Typless

• •

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


Local and Global Scope Program (

#!/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

#Changing a global variable

#Using just local variables

#Using a global variable name

Python Programming


Program Results

outside x before call: 6 Global sum= 30 outside x after call: 30 Local sum= 12

outside a before call: 33 No sum= 11 outside a after call: 33

Python Programming


Connection between Actual and Dummy Arguments

• •

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


Demo Code (
#!/usr/bin/python s='adamantium' print 'String before function call: ',s def attempt(t): t='helium'; return t #String immutable back=attempt(s) print 'function returned ',back print 'String after function call: ',s nums=[2,635.8,'eight',44,12.34] print 'List before function call: ',nums def morph(vector): vector[2]=8; return vector #List mutable back=morph(nums) print 'function returned ',back print 'List after function call: ',nums

Python Programming


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


Keywords and Defaults for Dummy Arguments

• •

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


Arguments with Keywords (
$ cat #!/usr/bin/python def integral(begin,end,acc): print 'begin= ', begin print 'end= ', end print 'acc= ', acc return integral(5.0,25.0,0.001) integral(acc=0.001,end=55.0,begin=10.0) integral(6.0,acc=0.001,end=38.0) $ begin= 5.0 end= 25.0 acc= 0.001 begin= 10.0 end= 55.0 acc= 0.001 begin= 6.0 end= 38.0 acc= 0.001

#Positional Matching #Keyword Matching #Combination

Python Programming


Arguments with Default Values (
$ cat #!/usr/bin/python def integral(begin=1.0,end=500.0,acc=0.001): print 'begin=', begin,'end=',end,'acc=',acc return integral(5.0,25.0,0.0000001) #No defaults used integral(3.0,18.0) #1 default used integral(5.0) #2 defaults used integral() #All defaults used #integral(,333.0,) #ILLEGAL $ begin= 5.0 end= begin= 3.0 end= begin= 5.0 end= begin= 1.0 end=

25.0 acc= 1e-07 18.0 acc= 0.001 500.0 acc= 0.001 500.0 acc= 0.001

Python Programming


Can Python functions return more than one value?

• •

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


Sample Python Program

$ cat #!/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

#Two-tuple returned #Two Lists receive

$ Merge list= ['proton', 'tonsil'] Length list= [6, 6] $

Python Programming


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.” (Don’t forget to capitalize the first letter!)

Python Programming


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


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


Use of the math installed Module
>>> import math #Importing math module >>> dir(math) #Provides a list of module attributes ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> help(math.sqrt) #Get terse definition of any function Help on built-in function sqrt: sqrt(...) sqrt(x) Return the square root of x. >>> radius=14.2 >>> area=math.pi*(radius**2); area #Using a module variable 633.47074266984589 >>> a=14.5; b=12.7 >>> c=math.sqrt(a**2+b**2); c #Using a module function 19.275372888740698

Python Programming


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


The Standard Module Library
• The math module we just used one of a vast (~200) collection of Python modules that come installed with Python. This amazingly diverse set of Python code is called the The Standard Library. It is impossible to list all of the topics covered in the Standard Library. There are low-level interfacing/control modules for your operating system, HTML, sockets, and all types of standardized inter-computer communication; modules containing extended operations on Pythons data types; random number modules; and various audio/visual support modules. Just to name a few. So how can I found out about the Standard Library? Three ways come to mind:
– – – Find the library directory for your particular Python installation and see what is there Browse the “Bible”: Python Library Reference Manual which may have come with your installation Browse this excellently-constructed Manuel on the Python web site


Python Programming


Library module bisect and Python command from

>>> 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


Writing your own Modules • Here is a demo module dealing with complex numbers written by the author.
$ cat 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


Using your own Modules

>>> 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


These have all been Objects?

Python Programming

EVERYTHING in Python is an Object
• Yes, it’s true. Beneath the hood of Python is OOP (Object-Oriented Programming). Everything is an object of a certain class. We have actually been creating a number objects, list objects, function objects, and module objects (to name a few) WHY? The OOP approach is very powerful at arranging related entities in a hierarchy, thus giving the language a clear structure. Most important, because of the hierarchy efficient code reuse occurs naturally through the process of inheritance. HOW? Types are declared in Python with a class definition. An object is just a variable of some class (an instantiation). Class definitions can contain data members and function members (which are also called methods). An object accesses any member with “dot” notation. That’s why we have been typing things like Ships.sort() WHY NOT TELL US? To show that you can use all the Python programming we have seen so far without knowing a whit about OOP. WHY TELL US? To provide a deeper understanding of Python which should enable more programming possibilities. But the real reason is …

• •

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

Classes and Objects

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:

class class_name: def method_name1(self,…) def method_name2(self,…)
• • Note that the class header and body have the same syntax as other code blocks in Python The keyword self must be the first argument of every class method. It is a reference to the specific object that is calling a method (For C++ programmers, think of this)

Python Programming


Class Rectangle

$ cat 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


Creating and Using Rectangle Objects
>>> from Figures import * >>> box=Rectangle() >>> box.setheight(23.5) >>> box.setwidth(12.5) >>> box.display() Height: 23.5 Width: 12.5 >>> box.area() >>> print "The area of the box is",box.area The area of the box is 293.75 >>> boundary=2.0*(box.height+box.width) #Script can directly access box’s data >>> print "The perimeter of the box is",boundary The perimeter of the box is 72.0

Python Programming


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


Overloading + (and a Constructor)
$ cat class Rectangle: def __init__(self,width=0.0,height=0.0): self.width=width self.height=height def area(self): self.area=self.height*self.width def display(self): print "Height:",self.height,"Width:",self.width def __add__(self,another): res=Rectangle() res.width=self.width+another.width res.height=self.height+another.height return(res)

Python Programming


Adding your own Objects
>>> from Figures import * >>> square=Rectangle(43.2,43.2) #Initialize square values >>> square.display() Height: 43.2 Width: 43.2 >>> rug=Rectangle(48.0,24.0) #Exactly the same as #Rectangle.__init__(rug,48.0,24.0) >>> rug.display() Height: 24.0 Width: 48.0 >>> total=square+rug #Rectangle.__add__(square,rug) >>> total.display() Height: 67.2 Width: 91.2 #Decided addition of two #Rectangle objects would mean #adding their heights and widths

Python Programming



Recall that in the first form of the Rectangle class that object’s 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