2. Page 1
Tutorial Overview
Part I
•Introduction
•Installing Python
•First steps
•Basic types: numbers, strings
•Container types: lists, dictionaries, Tuples
Part II
• Variables
•Control structures
•Functions
•Modules
Part III
•Exceptions
•Data Structures
•Files & standard library
3. Page 2
What is Python
Python is an interpreted, interactive, object oriented programming
language. Python can be compared to PERL, TCL or Java.
Part I Introduction
4. Page 3
Why is Python
Part I Introduction
1) Easy to Use and Easy to Learn
2) High Level: When you write programs in Python, you never need to bother
about the low-level details such as managing the memory used by your
program, etc.
3) Open Source Language
4) Portable : Works on Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2,
AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC
OS, VxWorks, PlayStation, Windows CE and even PocketPC.
5) Object Oriented
6) Powerful to use: It has various libraries which supports databases, network,
Internet, XML, GUI, HTML, CGI, FTP, email etc…
7) Embeddable: You can embed Python within your C/C++ programs to give
'scripting' capabilities to the users.
Finally: Batteries Included
__________________________________________________________________________________
No other language has made me more productive than Python. Python is perhaps the only one language
that focuses on making things easier for the programmer.
-- Bruce Eckel author of the famous 'Thinking in Java' and 'Thinking in C++' books.
Python has always been an integral part of Google
---Peter Norvig ( Lisp author and Director of Search Quality at Google )
Python has beaten contenders like Perl and Ruby to become the main programming that will be supported by
UserLinux -- Bruce Perens (co-founder of OpenSource.org)
5. Page 4
How to Use Python
Installation
Python can be installed from the following web pages.
http://www.python.org/download (Core Python)
http://www.activestate.com (Active Python)
Currently downloadable versions are –
Python 2.4
Python 2.5
Active Python :
In addition to core Python build, ActivePython includes a suite of
tools and resources to enhance Python programming productivity
1) The PyWin32 Windows Extensions interface to the Win32 API.
2) PythonCOM for integrating Python with COM and ASP.
3) Pythonwin Development Environment, for the Windows platform
Part I Introduction
7. Page 6
Types of Interfaces
When you install python we get 2 interfaces through which we can start writing
python commands.
1) Python's interactive shell (command line).
2) Pythonwin IDLE (Integrated DeveLopment Environment)
Part I – First Steps
Types of Interfaces
8. Page 7
Interactive Mode
Types of Interfaces
When you install python we get 2 interfaces through which we can start
writing python commands.
1) Python's interactive shell (command line).
2) Pythonwin IDLE (Integrated DeveLopment Environment)
When commands are read from a terminal, the interpreter is said
to be in interactive mode.
In this mode it prompts for the next command with the primary
prompt, usually three greater-than signs (">>> ")
For continuation lines it prompts with the secondary prompt, by
default three dots ("... ").
The interpreter prints a welcome message stating its version
number and a copyright notice before printing the first prompt:
Part I – First Steps
11. Page 10
Hands On
Use Python AS calculator
Type statements or expressions at prompt:
>>>print "Hello, world"
Hello, world
>>> x = 12**2
>>> print x/2
72
>>> # this is a comment
>>> width=20
>>> height=5*9
>>> width* height
Part I – First Steps
12. Page 11
The Basic types
Numbers
•The interpreter acts as a simple calculator: you can type an expression
and it will give the results.
>>> 2+2
•A value can be assigned to several variables simultaneously
>>> x = y = z = 0 # Zero x, y and z
•There is full support for floating point
•operators with mixed type operands convert the integer operand to
floating point:
>>> 3 * 3.75 / 1.5 output7.5
>>> 7.0 / 2 output->3.5
•Complex numbers are also supported
>>> (3+1j)*3
(9+3j)
Part I – Basic Types
13. Page 12
Operators
Numeric Operators
Unary operators
+, - , ~ (inversion operator)
Binary operators
+ , - , * / , % , **
Binary Bitwise Operations
& (AND), | (OR), ^ (XOR)
Shifting Operators
<< , >>
for x in range(0,-10,-1): print x,~x
Other functions
• abs(x) This function takes absolute value of any integer
• divmod(a,b) This performs division and returns quotient and remainder
• pow(x,y[z]) Calculates the “power-of” (z performs modulo operation)
• Round(x,[y]) Rounds the floating point number
• min(x,y,…)
• max(x,y,..)
• cmp(x,y)
15. Page 14
• Strings can be subscripted (indexed)
• Like in C, the first character of a string has subscript (index) 0.
• There is no separate character type;
• A character is simply a string of size one.
• An omitted first index defaults to zero, an omitted second index defaults
to the size of the string being sliced
>>> “hello”[:2] ‘he' # The first two characters
>>> “hello”[2:] ‘llo’ #Except the first two characters
Indices may be negative numbers, to start counting from the right. For
example:
>>> “hello”[-1] ‘0' # The last character
>>> “hello”[-2] ‘l' # Last but one character
>>> “hello”[-2:] ‘lo' # The last two characters
>>> “hello”[:-2] ‘hel' # Except the last two
characters
More on Strings
Part I – Basic Types
H E L L O
0 1 2 3 4
-5 -4 -3 -2 -1
16. Page 15
Variables
Variables are the identifiers which can hold any type of data.
No need to declare
Need to assign (initialize)
use of uninitialized variable raises exception
Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
Everything is a "variable":
Even functions, classes, modules
Part I – Variables
17. Page 16
Hands On
Part I – Hands on
Use PythonWin editor and create a Script
Use notepad to create Python script
Use Advanced Editors (Eclipse-PyDev) to create the Python Scripts
Exercise
Write programs using
PythonWin
Notepad
Eclipse
Write a Python script to take input from the user and display the output using
PythonWin
Notepad
19. Page 18
Lists
List is an ordered collection of zero or more elements.
An element of a list can be any sort of object.
These are comma seperated values enclosed in SQAURE Brackets[].
Also called as Flexible arrays
a = [99, "bottles of beer", ["on", "the", "wall"]]
Same operators as for strings
a+b, a*3, a[0], a[-1], a[1:], len(a)
Item and slice assignment
a[0] = 98
a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]
del a[-1] # -> [98, "bottles", "of", "beer"]
Part I – Container Types
20. Page 19
More List Operations
>>> a = range(5) # [0,1,2,3,4]
>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]
5
>>> a.insert(0, 42) # [42,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]
>>> a.index(4) # 4
>>> del a[ : ]
Part I – Container Types
21. Page 20
Using Lists
List can be used as a stack which is based on the principle “last-in,
first-out” .
>>> stack = [3, 4, 5] >>>stack. Pop()
>>> stack.append(6) stack=[3,4,5,6]
>>> stack.append(7) >>>stack. Pop()
Stack=[3,4,5,6,7] stack=[3,4,5]
List can also be used as a queue based on the principle “first-in, first-
out”.
>>>queue=[“Eric”, ”John”, “Michael”]
>>>queue. Append (“Terry”)
queue=[“Eric”, “John”, “Michael”, “Terry”]
>>>queue. Pop(0)
queue=[“John”, “Michael”, ”Terry”]
Part I – Container Types
22. Page 21
Tuples
A tuple consists of a set of values separated by commas and enclosed
by Parenthesis “()”.
It is similar to Lists.
The difference is that Tuples are Immutable.
>>> t =(12345, 54321, 'hello!') # parentheses optional
>>> # Tuples may be nested:
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
t = 12345, 54321, 'hello!' #tuple packing
x, y, z = t # tuple unpacking
singleton = (1,) # Note trailing comma!!!
empty = () # parentheses!
**Strings and Tuples are immutable
Part I – Container Types
23. Page 22
Dictionaries
Dictionary is a Python object that cross-references keys to values.
A Key is an immutable object such as a string
Dictionaries are unordered set of “key-value” pairs
Also called as "associative arrays“
d = {"duck": "eend", "water": "water"}
Lookup:
d["duck"] -> "eend"
d["back"] # raises KeyError exception
Delete, insert, overwrite:
del d["water"] # {"duck": "eend“}
d["back"] = "rug" # {"duck": "eend", "back": "rug"}
d["duck"] = "duik" # {"duck": "duik", "back": "rug"}
Part I – Container Types
24. Page 23
More Dictionary Ops
Keys, values, items:
d.keys() -> ["duck", "back"]
d.values() -> ["duik", "rug"]
d.items() -> [("duck","duik"), ("back","rug")]
Presence check:
d.has_key("duck") -> True
d.has_key("spam") -> False
Values of any type; keys almost any
{"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
Part I – Container Types