Python 1
Python 1
Python 1
Rohit Pawar
Vivek Sahu
Overview
History
Installing & Running Python
Names & Assignment
Sequences types: Lists, Tuples, and
Strings
Mutability
Why Python?
Python is Efficient
Python is Fast
Python is Broad
Python is not Python
Python is Easy
Installing
Installing Python is generally easy. Download
from http://python.org/download/ and install it.
Python is pre-installed on most Unix systems,
including Linux and MAC OS X.
Python comes with a large library of standard
modules.
PyPi
Repository of software for python
programming language.
To install any Python package run
command pip install <package-name>
List Comprehension
It is a process of forming lists
out of other lists or structures
Slicing
Slicing is the process of taking a subset of some data
It is most commonly applied to strings and lists
Python Scripts
When you call a python program from the
command line the interpreter evaluates each
expression in the file
Familiar mechanisms are used to provide
command line arguments and/or redirect
input and output
Python also has mechanisms to allow a
python program to act both as a script and as
a module to be imported and used by another
python program
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
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
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)
78865786736479050355236321393218507000000L
>>> 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
Indentation matters to code meaning
Block structure indicated by indentation
First assignment to a variable creates it
Variable types dont need to be declared.
Python figures out the variable types on its own.
Assignment is = and comparison is ==
For numbers + - * / % are as expected
Special use of + for string concatenation and % for
string formatting (as in Cs printf)
Logical operators are words (and, or,
not) not symbols
The basic printing command is print
Basic Datatypes
Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
Floats
x = 3.456
Strings
Can use or to specify with abc ==
abc
Unmatched can occur within the string:
matts
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
Use \ when must go to next line prematurely
No braces {} to mark blocks of code, use
consistent indentation instead
First line with less indentation is outside of the block
First line with more indentation starts a nested block
Colons start of a new block in many constructs,
e.g. function definitions, then clauses
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 a variable in Python means setting a name to
hold a reference to some object
Assignment creates references, not copies
Names in Python do not have an intrinsic type,
objects have types
Python determines the type of the reference automatically
based on what data is assigned to it
You create a name the first time it appears on the left
side of an assignment expression:
x = 3
A reference is deleted via garbage collection after
any names bound to it have passed out of scope
Python uses reference semantics (more later)
Naming Rules
Names are case sensitive and cannot start
with a number. They can contain letters,
numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
There are some reserved words:
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
joined_lower for functions, methods and,
attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing
conventions
Attributes: interface, _internal, __private
Assignment
You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
Assignments can be chained
>>> a = b = x = 2
Accessing Non-Existent Name
Accessing a name before its been properly
created (by placing it on the left side of an
assignment), raises an error
>>> y
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> Hello * 3
HelloHelloHello
Mutability:
Tuples vs. Lists
Lists are mutable
>>> li.insert(2, i)
>>>li
[1, 11, i, 3, 4, 5, a]
The extend method vs +
+ creates a fresh list with a new memory ref
extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, i, 3, 4, 5, a, 9, 8, 7]
Potentially confusing:
extend takes a list as an argument.
append takes a singleton as an argument.
>>> 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.sort(some_function)
# sort in place using user-defined comparison
Tuple details
The comma is the tuple creation operator, not parens
>>> 1,
(1,)