Documente Academic
Documente Profesional
Documente Cultură
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?
Python Programming 4
Basic Operation
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.
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
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
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
>>> x=6666666666444444448882222222990000004444444882119L
>>> y=5555999999997777777777222163489390372039309309L
>>> x+y
6672222666444442226659999445153489394816484191428L
>>> 5**100
7888609052210118054117285652827862296732064351090230047702789306640625L
>>>
Python Programming 18
Displaying Floating-Point Numbers
>>> 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
Python Programming 20
The “Amazing” Assignment Operator
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
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)
Python Programming 25
String Operators
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
>>>
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
Python Programming 30
Interlude: Printing to the Standard Output
Python Programming 31
Printing Formatted Strings
Python Programming 32
Interlude: Can we provide input to Python programs?
Python Programming 33
The read.py Script
#!/usr/bin/python
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
Python Programming 36
Immutable Strings????
Python Programming 37
Changing Strings
Python Programming 38
String Methods
Python Programming 39
Using String Methods
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
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:
Python Programming 44
Lists growing and shrinking (basic techniques)
Python Programming 45
Lists growing and shrinking (using methods)
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
Python Programming 48
is accessAtt tyvia whonary keyonshC BT/TT1as
• 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
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, …}
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
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
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.
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
Python Programming 58
Exercise Set 1
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
Python Programming 62
Relational Boolean Operators
Python Programming 63
Logical Boolean Operators
• In the following table, b and d are anything that evaluates to true or false
Operator Meaning
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
• 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
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 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 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
Python Programming 75
The for Loop
• Python work-horse unconditional loop: it can iterate through items in strings, lists,
and tuples. Syntax:
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
Python Programming 77
Some more for Loops
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
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
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:
• 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)
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
Local sum= 12
Python Programming 91
Connection between Actual and Dummy Arguments
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
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?
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
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!
sqrt(...)
sqrt(x)
• 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
• Here is a demo module dealing with complex numbers written by the author.
$ cat modern.py
print "Beginning import"
def partner(c):
res=complex(c.real,-c.imag) #Module method
return(res)
=243.9jdules
)
d
u
l
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 …
• 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
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)
$ 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
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)
• 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