Python
Python
PYTHON
By,
Anand Roy Choudhury
CSE Department,
IIT Bombay.
Overview
History
Assignment and Name conventions
Basic Data types
Sequences types: Lists, Tuples, and
Strings
Mutability
Modules
Errors and Exceptions
Running Python
>>>
On Unix:
% python
>>> 3+3
6
>>>
On Unix:
% python
>>> 3+3
6
Example :
interpreter
>>> python intern.py
directly executable by
The Basics
Basic Datatypes
Are Immutable
4 types :
Long
Int
complex (complex numbers)
Floats x = 3.456
Strings
Can use or to specify with abc == abc
Unmatched can occur within the string:
m atts
Use triple double-quotes for multi-line strings or
strings than contain both and inside of them:
abc
Whitespace
Whitespace is meaningful in Python:
especially indentation and placement of
newlines
Use a newline to end a line of code
l
Comments
Start comments with #, rest of line is
ignored
Can include a documentation string as
the first line of a new function or class
you define
Development environments, debugger,
and other tools use it: its good style to
include one
def fact(n):
fact(n) assumes n is a positive integer
and returns facorial of n.
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Assignment
Binding
x = 3
Naming Rules
Names are case sensitive and cannot start
Assignment
You can assign to multiple names at
>>> x, y = 2, 3
>>> x
2
>>> y
3
Control Flow
The While statement
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
for Statements
Control Flow
The if statement
x = int(input("Please enter an integer: "))
if x < 0:
x=0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
range() Function
for i in range(5):
print i
Control Flow
Functions
Defining Functions:
>>> def fib(n):
# write Fibonacci series up to n.Print a Fibonacci
series up to n.
...
a, b = 0, 1
...
while a < n:
...
print a,
...
a, b = b, a+b
...
print
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1597
Keyword Arguments
Functions can be called using
Function Call
This function can be called in any of the
following ways:
parrot(1000)
parrot(voltage=1000)
parrot(voltage=1000000,
# 1 positional argument
# 1 keyword argument
action='VOOOOOM')
#2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)
# 2 keyword arguments
parrot('a
parrot('a
# 3 positional arguments
# 1 positional, 1 keyword
Java vs Python
JAVA
23
PYTHON
Sequence types:
Tuples, Lists, and
Strings
Sequence Types
1.Tuple: (john, 32, [CMSC])
A simple immutable ordered sequence
of items
Items can be of mixed types, including
collection types
2.Strings: John Smith
Immutable
Conceptually very much like a tuple
Similar Syntax
All three sequence types (tuples,
Sequence Types 1
Define tuples using parentheses and
commas
>>> tu = (23, abc, 4.56, (2,3), def)
and commas
>>> li = [abc, 34, 4.34, 23]
= Hello World
= Hello World
= This is a multi-line
that uses triple quotes.
Sequence Types 2
Access individual members of a tuple,
>>> t[:]
(23, abc, 4.56, (2,3), def)
Note the difference between these two
lines for mutable sequences
>>> l2 = l1 # Both refer to 1 ref,
# changing one affects both
>>> l2 = l1[:] # Independent copies,
two refs
The in Operator
Boolean test whether a value is inside a
container:
>>> t
>>> 3
False
>>> 4
True
>>> 4
False
= [1, 2, 4, 5]
in t
in t
not in t
The + Operator
The + operator produces a new tuple, list, or
string whose value is the concatenation of its
arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> Hello + + World
Hello World
The * Operator
new tuple, list, or
string that repeats the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> Hello * 3
HelloHelloHello
Mutability:
Tuples vs. Lists
The
>>> li.sort()
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Tuple details
The comma is the tuple creation operator, not
parentheses
>>> 1,
(1,)
MODULES
What is a Module?
fibo.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
print
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
MODULE
Now enter the Python interpreter and import this module with
the following command:
>>> import fibo
This does not enter the names of the functions defined
infibodirectly in the current symbol table; it only enters the
module namefibothere. Using the module name you can access
the functions:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
Handling Exception
It is possible to write programs that handle selected
exceptions. Look at the following example, which asks the user
for input until a valid integer has been entered, but allows the
user to interrupt the program (usingControl-Cor whatever the
operating system supports); note that a user-generated
interruption is signalled by raising theKeyboardInterrupt
exception.
>>> while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
Handling Exception
Thetrystatementworksasfollows.
First,thetryclause(thestatement(s)between
thetryandexceptkeywords)isexecuted.
If no exception occurs, theexcept clauseis skipped and
execution of thetrystatement is finished.
If an exception occurs during execution of the try clause,
the rest of the clause is skipped. Then if its type matches
the exception named after the exceptkeyword, the
except clause is executed, and then execution continues
after thetrystatement.
If an exception occurs which does not match the
exception named in the except clause, it is passed on to
outertrystatements; if no handler is found, it is
anunhandled exceptionand execution stops.
End
.Thank You