Introduction to Python
S.Madhumalar
Assistant Professor
C.P.A College, Bodinayakanur
Brief History of Python
Python’s Benevolent Dictator For Life
“Python is an experiment in how much freedom program-mers need. Too much freedom and nobody can read another's code; too little and expressive-ness is endangered.”
- Guido van Rossum
Running Python
The Python Interpreter
[finin@linux2 ~]$ python
Python 2.4.3 (#1, Jan 14 2008, 18:32:40)
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>>
Installing
IDLE Development Environment
Editing Python in Emacs
Running Interactively on UNIX
On Unix…
% python
>>> 3+3
6
Running Programs on UNIX
% python fact.py
#!/usr/bin/python
% chmod a+x fact.py
% fact.py
Example ‘script’: fact.py
#! /usr/bin/python
def fact(x):�"""Returns the factorial of its argument, assumed to be a posint"""
if x == 0:
return 1
return x * fact(x - 1)
print ’N fact(N)’
print "---------"
for n in range(10):
print n, fact(n)
Python Scripts
Example of a Script
#! /usr/bin/python
""" reads text from standard input and outputs any email� addresses it finds, one to a line.
"""
import re
from sys import stdin
# a regular expression ~ for a valid email address
pat = re.compile(r'[-\w][-.\w]*@[-\w][-\w.]+[a-zA-Z]{2,4}')
for line in stdin.readlines():
for address in pat.findall(line):
print address
results
python> python email0.py <email.txt
bill@msft.com
gates@microsoft.com
steve@apple.com
bill@msft.com
python>
Getting a unique, sorted list
import re
from sys import stdin
pat = re.compile(r'[-\w][-.\w]*@[-\w][-\w.]+[a-zA-Z]{2,4}’)
# found is an initially empty set (a list w/o duplicates)
found = set( )
for line in stdin.readlines():
for address in pat.findall(line):
found.add(address)
# sorted() takes a sequence, returns a sorted list of its elements
for address in sorted(found):
print address
results
python> python email2.py <email.txt
bill@msft.com
gates@microsoft.com
steve@apple.com
python>
Simple functions: ex.py
"""factorial done recursively and iteratively"""
def fact1(n):
ans = 1
for i in range(2,n):
ans = ans * n
return ans
def fact2(n):
if n < 1:
return 1
else:
return n * fact2(n - 1)
Simple functions: ex.py
671> python
Python 2.5.2 …
>>> import ex
>>> ex.fact1(6)
1296
>>> ex.fact2(200)
78865786736479050355236321393218507…000000L
>>> ex.fact1
<function fact1 at 0x902470>
>>> fact1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fact1' is not defined
>>>
The Basics
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
Enough to Understand the Code
Basic Datatypes
z = 5 / 2 # Answer 2, integer division
x = 3.456
Whitespace
Whitespace is meaningful in Python: especially indentation and placement of newlines
Use \ when must go to next line prematurely
Comments
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
Naming Rules
bob Bob _bob _2_bob_ bob_2 BoB
and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while
Naming conventions
The Python community has these recommend-ed naming conventions
Assignment
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
>>> a = b = x = 2
Accessing Non-Existent Name
Accessing a name before it’s been properly created (by placing it on the left side of an assignment), raises an error
>>> y
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
Sequence types: Tuples, Lists, and Strings
Sequence Types
Similar Syntax
Sequence Types 1
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> li = [“abc”, 34, 4.34, 23]
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
Sequence Types 2
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
>>> st = “Hello World”
>>> st[1] # Second character in string.
‘e’
Positive and negative indices
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Positive index: count from the left, starting with 0
>>> t[1]
‘abc’
Negative index: count from right, starting with –1
>>> t[-3]
4.56
Slicing: return copy of a subset
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Return a copy of the container with a subset of the original members. Start copying at the first index, and stop copying before second.
>>> t[1:4]
(‘abc’, 4.56, (2,3))
Negative indices count from end
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
Slicing: return copy of a =subset
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Omit first index to make copy starting from beginning of the container
>>> t[:2]
(23, ‘abc’)
Omit second index to make copy starting at first index and going to end
>>> t[2:]
(4.56, (2,3), ‘def’)
Copying the Whole Sequence
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
>>> l2 = l1 # Both refer to 1 ref,
# changing one affects both
>>> l2 = l1[:] # Independent copies, two refs
The ‘in’ Operator
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
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
>>> (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
Lists are mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li�[‘abc’, 45, 4.34, 23]
Tuples are immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
Operations on Lists Only
>>> li = [1, 11, 3, 4, 5]
>>> li.append(‘a’) # Note the method syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]
>>> li.insert(2, ‘i’)
>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
The extend method vs +
>>> li.extend([9, 8, 7])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Operations on Lists Only
Lists have many methods, including index, count, remove, reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
Operations on Lists Only
>>> li = [5, 2, 6, 8]
>>> li.reverse() # reverse the list *in place*
>>> li
[8, 6, 2, 5]
>>> li.sort() # sort the list *in place*
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Tuple details
>>> 1,
(1,)
>>> (1,)
(1,)
>>> (1)
1
>>> ()
()
>>> tuple()
()
Summary: Tuples vs. Lists
li = list(tu)
tu = tuple(li)