Python Programming
Science & Technology
Support Group
20-21 February 2007
Python Programming
Instructor
Peter G. Carswell
Supercomputer Resource Specialist
Ohio Supercomputer Center
(614) 292-1091
3Python 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
4Python 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
•Extremelyuseful 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
5Python 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
7Python 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.
[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
$
8Python 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 rabbit.py.
Here’s how it would be run:
Notice that only the text directly written out to stdout will appear on your monitor
$ python rabbit.py
Hello World! (with
respect)
1.04
$
9Python 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 rabbit.py file
#!<full pathname of Python executable>
– Second, give rabbit.py executable permission
$ chmod u+x rabbit.py
• Now the rabbit file looks like this:
• To run the commands in the rabbit.py file, just type its name at the system
prompt
#!/usr/local/bin/python
print "Hello World! (with respect)"
a=34.5
a
a*5.6
z=a/33.3
print '%7.2f' %(z)
$ rabbit.py
Hello World! (with respect)
1.04
Python Programming
Variables, Data Types and Operators
11Python 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 ….
12Python 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
13Python Programming
Numbers in Python
Type Examples
Decimal Integers
10 -235
Octal and Hexadecimal Integers
034723 0x3DE56A
Long Integers
(unlimited size)
777888207468890L
Floating-Point
3.45 6.2e-15 4E23
Complex
6.2+3J 5+8.7j
14Python 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.
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
15Python 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
>>>
$
16Python 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)
$
17Python Programming
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 literals have leading 0
'010742'
>>> hex(num) #Hex literals have leading 0x
'0x11e2'
>>>
18Python 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
>>>
19Python 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'
>>>
20Python Programming
Complex Numbers
>>> 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
>>>
• 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.
21Python 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
22Python 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
23Python 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
24Python 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
>>>
25Python 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
>>>