Short introduction to Python 3.2 (Spring 2012):
(2.X may be slightly different)
References:
- Python Tutorial
- (Lutz) (functions) 299-304
- (Lutz) Chapter 10 (Intro & loops) 201-215 (focus on 206-211)
Getting
started:
New scripts:
- Open IDLE (Python Developement tool) (On windows: from the "Start
Menu") . This opens a "Python Shell" window.
- Pull down the File menu and click on "New Window". This
opens the editor.
- In the "Edit Window", save the empty text in a file with an
extension .py. This will format your script as you type.
- To run the script from the "Edit Window", pull down the "Run"
menu and click on "Run Module. The script will execute t in
the "Python Shell" window.
Existing scripts:
- Right click on file and select "Edit with Idle".
There a many other ways to edit and run Python, including not using
IDLE.
Some important language features:
- Multi-paradigm language
- Object orientation, structured programming,
functional programming, aspect-oriented programming, and more recently, design
by contract are all supported.
- dynamically typed
- -- no declaration of variables
- -- type "lives" with objects, not names
- OO and functional
- reference model like Java
- Layout rule: White spaces delimit blocks of code instead of symbols like "{}" in C or keywords like begin and end in Pascal.
- IDLE will automatically format according to the layout rule.
- Notice the use of ":" in for, while, def and if statements.
- and -- logical and operator
not -- logical negation operator - elif can be used for "optional parts"
- if n < 5:
return 10
elif n < 20:
return 100
else:
return 1000
Example code:
fib.py
# Recursive definition of the nth fibonacci number
def fib (n):
if n < 2:
return 1
else :
return fib(n-1) + fib (n-2)
# Iterative definition
def fibi (n):
a = 1
b = 1
s = 1
while s < n:
s += 1
t = a + b
a = b
b = t
return b
# using for loop
def fibf (n):
a = 1
b = 1
for i in range (2,n+1): # i assumes the values 2 to n
t = a + b
a = b
b = t
return b