Sunteți pe pagina 1din 121

Python Programming

Science & Technology


Support Group

20-21 February 2007


Instructor

Peter G. Carswell
Supercomputer Resource Specialist
Ohio Supercomputer Center
pete@osc.edu
(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 3
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: www.python.org

Python Programming 4
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 5
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.

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

Python Programming 7
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 rabbit.py.
Here’s how it would be run:
$ python rabbit.py
Hello World! (with
respect)
1.04
$

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

Python Programming 8
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 rabbit.py file
#!<full pathnamTj/TT 98r eExecutabl>s

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 11
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 12
Numbers in Python

Type Examples
Decimal Integers 10 -235

Octal and Hexadecimal Integers 034723 0x3DE56A

Long Integers 777888207468890L


(unlimited size)
Floating-Point

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 Name
+x -x Unary Operators

x**y Exponentiation

x*y x%y x/y x//y Multiplication, modulus,


normal division, truncating
division
x + y x-y Addition, Subtraction

Python Programming 14
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 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

Python Programming 16
Alternative Integer Bases

>>> num=4578
>>> int(num)
4578
>>> int(67.345) #Truncating Conversion
67
>>> round(67.899) #Can “round-up”
68.0
>>> oct(num) #Octal li7 6 als hae Ileadng C

Python Programming 17
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 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 pl aces (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

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
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 23
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 24
Making String (II)

>>> totab="Dalton\tEnnis"; print totab #Escape Character


Dalton Ennis
>>> ornottotab=r"Dalton\tEnnis"; print ornottotab #Raw String
Dalton\tEnnis

Python Programming 25
String Operators

Expression What Happens


str1 + str2 Concatenation
str *n n*str Replication (n is an integer)
str[i] String element with index i
str[i:j] Substring of consecutive elements
(i to j-1)
len(str) Number of characters in a string
max(str) Maximum element (ASCII value)
min(str) Minimum element (ASCII value)

Python Programming 26
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 27
Finish theWork

>>> print len(rur) # Number of elements


19
>>> print max(rur) # ASCII code for ‘t’= 116
t
>>> print min(rur) # 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 doesn’t know what to do. Same vice versa.

Python Programming 29
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 30
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 31
Printing Formatted Strings

• For formatted output, use print control_string %


(variable_list)
– Works just like the C function printf
– The

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)

Python Programming 33
The read.py 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 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 %

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(in t), 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
Using String Methods

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

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
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 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
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,resize; Cannot appe Bthis way000000000002,

Python Programming 45
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 46
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 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 eac h of the three rows
6

Python Programming 48
is accessAtt tyvia whonary keyonshC BT/TT1as

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

Python Programming 49
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 50
Using Basic Dictionary Operands

>>> 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
10 # Syntax {key:value, key:value, …}

>>> top['pres']='F.D.R.'; top; len(top) #Can add a new pair


{'bio': 'Watson', '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.'}
11 #len operator works for dictionaries

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

Methods for Working with Dictionaries

>>> birth.get(50) #Get the value paired with key


argument
'kris'
>>> birth.popitem ()

Python Programming 53
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 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']='shawk@astroph.cit.edu'; student #Add new item
{'course': 'Astronomy 674', 'email': 'shawk@astroph.cit.edu', '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
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 56
Using Tuple Operators

>>> beatles=('Lennon','McCartney','Starr','Harrison','Martin');
#Parentheses () create tuples
>>> copyright=beatles[0]+' and ' +beat

Python Programming 57
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 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

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 actualm to e

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
Relational Boolean Operators

Operator Symbol Meaning


< Strictly less than
> Strictly greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
a in Box a is an element of Box
a not in 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 Meaning

not b Reverses logical state of b.


If b true, not b is false
and vice versa
b and d True if b and d both true.
False otherwise

b or d True if b is true, d is true


or both are true

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

Python Programming 64
Example Code

>>> 3.2 < 1.2, 234 > 12, "Draco" >= 'Draco', 'courts'<='course'
(0, 1, 1, 0) #Numbers and strings
>>> [1345,'Pyrite',4.56] >= [1345,'Pyrite',4.562]

Python Programming 65
FINALLY, syntax appealing Range Checking

>>> lower=16
>>> upper=88
>>> x=33
>>> x>lower and x<upper #Traditional syntax
1
>>> lower < x < upper #Yes, this is legal now
1
>>> x=5
>>> lower < x < upper
0
>>> x=16
>>> lower <= x <= upper
1
>>>

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
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 68
Putting if/else in a Python Script

$ cat ifblank.py
#!/usr/bin/python

now=2005
birth=raw_input('Please enter your birth year: ')
birth=int(birth)
if (now-birth) >= 21:
print 'You are of m8t0iluEMoeo 1 -13.98 0 258.1214 132.0598 22wMC so6TqT1 1 T58

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: Dickens
God Bless us everyone
$ author.py
Please enter the name of an author: Faulkner
The Past isn't dead.
It's not even past.
$ author.py
Please enter the name of an author: Melville
Moby is a direct descendent
$ author.py
Please enter the name of an author: Steele
Haven't heard of that writer
$

Python Programming 72
The while Loop

• Python’s conditional loop. General syntax is:

where the <entry condition> is the controlling Boolean expression.

Operation: While the entry condition is tru.26 Tm63 l

Python Programming 73
Random Walk while Loop

$ 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
Take a walk on the Random side

Flip a coin. Enter h or t: h


Flip a coin. Enter h or t: t
Flip a coin. Enter h or t: t
Flip a coin. Enter h or t: h
Flip a coin. Enter h or t: t
Flip a coin. Enter h or t: h
Flip a coin. Enter h or t: t
Flip a coin. Enter h or t: t
Flip a coin. Enter h or t: t
You took 9 steps

Python Programming 75
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 76
Some for Loops

>>> for num in [1,2,3,4,5]: #Normal integer loop variable


... num=num**2
... print num, #Suppress automatic carriage return
...

Python Programming 77
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 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

>>> for num in range(1,6):


... num=num**2
... print num,
• So our offending for loop becomes:
...
1 4 9 16 25

Python Programming 79
“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 80
>>> 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

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

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_nam e>(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 86
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 87
Simple Function Use

$ cat fctn.py
#!/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
$ fcn.py
scale_sum returned 75
scale_sum returned -9.2402
scale_sum returned Hip Hip Horray Hip Hip Horray Hip Hip Horray
$

Python Programming 88
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 uso n n
scale_sum
• This is an example of a broader concept callo nPolymorphism: the
meaning of code depends upon the types of the variables being uso .
• Having a function (with the same name) work with different actual
argument types is supporto n n other languages by generic functions, and
template functions.

Python Programming 89
Local and Global Scope Program (scope.py)

#!/usr/bin/python
x=6
print 'outside x before call: ',x
def gsum(y,z):
global x #Changing a global variable
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 #Using just local variables
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 #Using a global variable name
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

outside a before call: 33


No sum= 11
outside a after call: 33

Python Programming 91
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 92
Demo Code (arg.py)

#!/usr/bin/python

s='adamantium'
print 'String before function call: ',s
def attempt(t):
t='helium'; return t #w 0 13. t1mutableTjETEMC /P <</MCID 56>>BDC BT/TT1

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
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 95
Arguments with Keywords (keyarg.py)

$ cat keyarg.py
#!/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) #Positional Matching
integral(acc=0.001,end=55.0,begin=10.0) #Keyword Matching
integral(6.0,acc=0.001,end=38.0) #Combination
$ keyarg.py
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

Python Programming 96
Arguments with Default Values (keydef.py)

$ cat keydef.py
#!/usr/bin/python
def integral(begin=1.0,end=500.0,acc=0.001):
print 'begin=', begin,'end=',end,'acc=',acc
return

Python Programming 97
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 98
Sample Python Program

$ 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) #Two-tuple returned
Merge,Length=more('pro','ton') #Two Lists receive
print "Merge list= ",Merge
print "Length list=",Length

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

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.” (Don’t 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
ed by ASCII value as is done by the built-in sort
9. Write a function called dict1,dict2)
in both of its arguments. If the same key

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


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 definit ion 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 104


•400(It1(s uldill pointTdiou1(ot thimpo/Amm toul Pyth a m
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” nm/Lprofcribainhe previemefor memberhon

functs5(tso workamesth iden/Aryamm tobe va. Thuioned us thi we t]/Tdill )T021 Tc 0

Python Programming 105


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

Python Programming 106


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


3
+
-
4
j m

=243.9jdules
)
d
u
l

Using your own Modules


e
s

>>> import modern


m.Cdules
Beginning import #import Runs executable statements
Import ended
>>> dir(modern) #Yes, works on your own modules
['C', '__builtins__', '__doc

Python Programming 109


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


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 116


Operator Overloading

Python Programming
Overloading + (and a Constructor)

$ cat Figures.py
class Rectangle:
def __init__(self,wi dth=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.hei ght+another.height
return(res)

Python Programming 119


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 120


Initialization

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

Python Programming 121

S-ar putea să vă placă și