Python Programming Language: By: Priyanka Pradhan
Python Programming Language: By: Priyanka Pradhan
Python Programming Language: By: Priyanka Pradhan
Language
By: Priyanka Pradhan
Priyanka Pradhan 1
Books include:
Priyanka Pradhan 4
Development Environments
IDE
1. PyDev with Eclipse
2. Komodo
3. Emacs
4. Vim
5. TextMate
6. Gedit
7. Idle
8. PIDA (Linux)(VIM Based)
9. NotePad++ (Windows)
10.Pycharm
Priyanka Pradhan 5
Web Frameworks
• Django
• Flask
• Pylons
• TurboGears
• Zope
• Grok
Priyanka Pradhan 6
Introduction
Priyanka Pradhan 7
Python features
• no compiling or linking
• rapid development cycle
• no type declarations
• simpler, shorter, more flexible
• automatic memory management
• garbage collection
• high-level data types and operations
Priyanka Pradhan 8
Contd..
• fast development
• object-oriented programming
• code structuring and reuse, C++
• embedding and extending in C
• mixed language systems
• classes, modules, exceptions,multithreading
• "programming-in-the-large" support
Priyanka Pradhan 9
Uses of Python
• shell tools
– system admin tools, command line programs
• extension-language work
• rapid prototyping and development
• language-based modules
– instead of special-purpose parsers
• graphical user interfaces
• database access
• distributed programming
• Internet scripting Priyanka Pradhan 10
Who Uses Python
• Google
• PBS
• NASA
• Library of Congress
• the ONION
• ...the list goes on...
Priyanka Pradhan 11
Python structure
• modules: Python source files or C extensions
– import, top-level via from, reload
• statements
– control flow
– create objects
– indentation matters – instead of {}
• objects
– everything is an object
– automatically reclaimed when no longer needed
Priyanka Pradhan 12
Indentation
Priyanka Pradhan 13
Hello World
Priyanka Pradhan 14
Python Overview
Priyanka Pradhan 15
The Python Interpreter
Priyanka Pradhan 16
The print Statement
•Elements separated by
commas print with a space
>>> print 'hello'
between them
hello
•A comma at the end of the
>>> print 'hello', 'there'
statement (print ‘hello’,) will
hello there
not print a newline character
Priyanka Pradhan 17
Documentation
Priyanka Pradhan 18
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Priyanka Pradhan 19
Everything is an object
• Everything means
>>> x = 7
everything, including
>>> x
functions and classes 7
(more on this later!) >>> x = 'hello'
• Data type is a property >>> x
of the object and not of 'hello'
>>>
the variable
Priyanka Pradhan 20
Basic operations
• Assignment:
– size = 40
–a = b = c = 3
• Numbers
– integer, float
– complex numbers: 1j+3, abs(z)
• Strings
– 'hello world', 'it\'s hot'
– "bye world"
Priyanka Pradhan 21
String operations
Priyanka Pradhan 23
Numbers: Floating Point
• int(x) converts x to an >>> 1.23232
integer 1.2323200000000001
>>> print 1.23232
• float(x) converts x to a 1.23232
floating point >>> 1.3E7
• The interpreter shows 13000000.0
>>> int(2.0)
a lot of digits
2
>>> float(2)
2.0
Priyanka Pradhan 24
Numbers: Complex
• Built into Python
• Same operations are >>> x = 3 + 2j
supported as integer and >>> y = -1j
>>> x + y
float
(3+1j)
>>> x * y
(2-3j)
Priyanka Pradhan 25
Numbers are immutable
x 4.5
>>> x = 4.5
>>> y = x y
>>> y += 3
x 4.5
>>> x
4.5 y 7.5
>>> y
7.5
Priyanka Pradhan 26
String Literals
Priyanka Pradhan 27
String Literals: Many Kinds
• Can use single or double quotes, and three double
quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘ Priyanka Pradhan 28
Substrings and Methods
• len(String) – returns the
>>> s = '012345'
number of characters in the
>>> s[3]
String
'3'
>>> s[1:4]
• str(Object) – returns a
'123'
String representation of the
>>> s[2:]
Object
'2345'
>>> s[:4] >>> len(x)
'0123' 6
>>> s[-2] >>> str(10.3)
'4' '10.3'
Priyanka Pradhan 29
String Formatting
• Similar to C’s printf
• <formatted string> % <elements to insert>
• Can usually just use %s for everything, it will
convert the object to its String representation.
>>> "One, %d, three" % 2
'One, 2, three'
>>> "%d, two, %s" % (1,3)
'1, two, 3'
>>> "%s two %s" % (1, 'three')
'1 two three'
>>>
Priyanka Pradhan 30
Do nothing
Priyanka Pradhan 31
Operators
• Arithmetic
Priyanka Pradhan 32
String Manipulation
Priyanka Pradhan 33
Logical Comparison
Priyanka Pradhan 34
Identity Comparison
Priyanka Pradhan 35
Arithmetic Comparison
Priyanka Pradhan 36
Class Declaration
Priyanka Pradhan 37
Class Attributes
Priyanka Pradhan 38
Class Methods
Priyanka Pradhan 39
Class Instantiation & Attribute
Access
Priyanka Pradhan 40
Class Inheritance
Priyanka Pradhan 41
Imports
Priyanka Pradhan 42
Error Handling
Priyanka Pradhan 43
Lists
• Ordered collection of data
• Data can be of different
>>> x = [1,'hello', (3 + 2j)]
types >>> x
• Lists are mutable [1, 'hello', (3+2j)]
>>> x[2]
• Issues with shared
(3+2j)
references and mutability >>> x[0:2]
• Same subset operations as [1, 'hello']
Strings
Priyanka Pradhan 44
List
• lists can be heterogeneous
– a = ['spam', 'eggs', 100, 1234, 2*2]
• Lists can be indexed and sliced:
– a[0] spam
– a[:2] ['spam', 'eggs']
• Lists can be manipulated
– a[2] = a[2] + 23
– a[0:2] = [1,12]
– a[0:0] = []
– len(a) 5 Priyanka Pradhan 45
List methods
• append(x)
• extend(L)
– append all items in list (like Tcl lappend)
• insert(i,x)
• remove(x)
• pop([i]), pop()
– create stack (FIFO), or queue (LIFO) pop(0)
• index(x)
– return the index for value x
Priyanka Pradhan 46
Contd…
• count(x)
– how many times x appears in list
• sort()
– sort items in place
• reverse()
– reverse list
Priyanka Pradhan 47
Lists: Modifying Content
• x[i] = a reassigns the >>> x = [1,2,3]
>>> y = x
ith element to the
>>> x[1] = 15
value a >>> x
• Since x and y point to [1, 15, 3]
the same list object, >>> y
[1, 15, 3]
both are changed
>>> x.append(12)
• The method append >>> y
also modifies the list [1, 15, 3, 12]
Priyanka Pradhan 48
Lists: Modifying Contents
>>> x = [1,2,3]
• The method >>> y = x
append modifies >>> z = x.append(12)
the list and returns >>> z == None
None True
• List addition (+) >>> y
returns a new list [1, 2, 3, 12]
>>> x = x + [9,10]
>>> x
[1, 2, 3, 12, 9, 10]
>>> y
[1, 2, 3, 12]
Priyanka Pradhan>>> 49
Strings share many features with
lists
>>> smiles = "C(=N)(N)N.C(=O)(O)O"
>>> smiles[0]
'C'
>>> smiles[1]
'('
>>> smiles[-1]
'O'
>>> smiles[1:5]
'(=N)'
>>> smiles[10:-4]
'C(=O)' Priyanka Pradhan 50
String Methods: find, split
smiles = "C(=N)(N)N.C(=O)(O)O"
>>> smiles.find("(O)")
15
>>> smiles.find(".")
9
>>> smiles.find(".", 10)
-1
>>> smiles.split(".")
['C(=N)(N)N', 'C(=O)(O)O']
>>>
Priyanka Pradhan 51
String operators: in, not in
if "Br" in “Brother”:
print "contains brother“
email_address = “clin”
if "@" not in email_address:
email_address += "@brandeis.edu“
Priyanka Pradhan 52
String Method: “strip”, “rstrip”, “lstrip” are
ways to
remove whitespace or selected characters
>>> line = " # This is a comment line \n"
>>> line.strip()
'# This is a comment line'
>>> line.rstrip()
' # This is a comment line'
>>> line.rstrip("\n")
' # This is a comment line '
>>>
Priyanka Pradhan 53
More String methods
email.startswith(“c") endswith(“u”)
True/False
>>> “chen".upper()
‘CHEN'
Priyanka Pradhan 54
“\” is for special characters
\n -> newline
\t -> tab
\\ -> backslash
...
But Windows uses backslash for directories!
filename = "M:\nickel_project\reactive.smi" # DANGER!
filename = "M:\\nickel_project\\reactive.smi" # Better!
filename = "M:/nickel_project/reactive.smi" # Usually works
Priyanka Pradhan 55
Tuples
• Tuples are immutable
versions of lists
• One strange point is the >>> x = (1,2,3)
format to make a tuple with >>> x[1:]
(2, 3)
one element:
>>> y = (2,)
‘,’ is needed to differentiate >>> y
from the mathematical (2,)
expression (2) >>>
Priyanka Pradhan 56
Tuples and sequences
Priyanka Pradhan 59
Contd..
• no particular order
• delete elements with del
>>> del tel['foo']
• keys() method unsorted list of keys
>>> tel.keys()
['cs', 'lennox', 'hgs']
• use has_key() to check for existence
>>> tel.has_key('foo')
0 Priyanka Pradhan 60
Dictionaries: Add/Modify
• Entries can be changed by assigning to that entry
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
• Assigning to a key that does not exist adds an entry
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
Priyanka Pradhan 61
Dictionaries: Deleting Elements
• The del method deletes an element from a dictionary
>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
Priyanka Pradhan 62
Copying Dictionaries and Lists
• The built-in list >>> l1 = [1] >>> d = {1 : 10}
function will >>> l2 = list(l1) >>> d2 = d.copy()
copy a list >>> l1[0] = 22 >>> d[1] = 22
>>> l1 >>> d
• The dictionary [22] {1: 22}
has a method >>> l2 >>> d2
called copy [1] {1: 10}
Priyanka Pradhan 63
Dictionary Methods
Priyanka Pradhan 64
Data Type Summary
Priyanka Pradhan 65
Contd…
Priyanka Pradhan 66
Modules
Priyanka Pradhan 69
Input: Example
print “enter your name?"
name = raw_input("> ")
print "Hi %s! You are %d years old!" % (name, 2017 - birthyear)
~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are Pradhan
Priyanka 31 years old! 70
Booleans
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0 respectively
Priyanka Pradhan 71
Boolean Expressions
• Compound boolean expressions >>> True and False
short circuit False
• and and or return one of the >>> False or True
elements in the expression True
>>> 7 and 14
• Note that when None is returned 14
the interpreter does not print >>> None and 2
anything >>> None or 2
2
Priyanka Pradhan 72
No Braces
• Python uses indentation instead of braces to
determine the scope of expressions
• All lines must be indented the same amount to be part
of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
Priyanka Pradhan 73
If Statements
import math
x = 30
if x <= 15 : >>> import ifstatement
y = x + 15 y = 0.999911860107
elif x <= 30 : >>>
y = x + 30 In interpreter
else :
y=x
print ‘y = ‘,
print math.sin(y)
In file ifstatement.py
Priyanka Pradhan 74
While Loops
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
In whileloop.py
7
8
9
>>>
In interpreter
Priyanka Pradhan 75
Loop Control Statements
Priyanka Pradhan 76
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x=1
~: python whileelse.py
while x < 3 : 1
print x 2
x=x+1 hello
else: Run from the command line
print 'hello'
In whileelse.py
Priyanka Pradhan 77
The Loop Else Clause
x=1
while x < 5 :
print x
x=x+1 ~: python whileelse2.py
break 1
else :
print 'i got here'
whileelse2.py
Priyanka Pradhan 78
For Loops
range(N) generatesPriyanka
a listPradhan
of numbers [0,1, …, n-1] 79
For Loops
• For loops also may have the optional else clause
for x in range(5):
print x
break
else : ~: python elseforloop.py
print 'i got here' 1
elseforloop.py
Priyanka Pradhan 80
Function Basics
Priyanka Pradhan 81
Functions are first class objects
• Can be assigned to a variable
• Can be passed as a parameter
• Can be returned from a function
• Functions are treated like any other variable in
Python, the def statement simply assigns a
function to a variable
Priyanka Pradhan 82
Function names are like any variable
>>> x = 10
>>> x
10
• Functions are objects >>> def x () :
• The same reference ... print 'hello'
rules hold for them as >>> x
for other objects <function x at 0x619f0>
>>> x()
hello
>>> x = 'blah'
>>> x
'blah'
Priyanka Pradhan 83
Functions as Parameters
Priyanka Pradhan 84
Higher-Order Functions
map(func,seq) – for all i, applies func(seq[i]) and returns the
corresponding sequence of the calculated results.
Priyanka Pradhan 85
Higher-Order Functions
Priyanka Pradhan 86
Higher-Order Functions
Priyanka Pradhan 87
Functions Inside Functions
• Since they are like any other object, you can have
functions inside functions
funcinfunc.py
Priyanka Pradhan 88
Functions Returning Functions
def foo (x) :
def bar(y) :
return x + y ~: python funcreturnfunc.py
return bar <function bar at 0x612b0>
# main 5
f = foo(3)
print f
print f(2)
funcreturnfunc.py
Priyanka Pradhan 89
Parameters: Defaults
• Parameters can be
>>> def foo(x = 3) :
assigned default ... print x
values ...
• They are overridden if >>> foo()
a parameter is given 3
>>> foo(10)
for them 10
• The type of the default >>> foo('hello')
doesn’t limit the type hello
of a parameter
Priyanka Pradhan 90
Parameters: Named
• Call by name
>>> def foo (a,b,c) :
• Any positional ... print a, b, c
arguments must ...
come before >>> foo(c = 10, a = 2, b = 14)
2 14 10
named ones in a
>>> foo(3, c = 2, b = 19)
call 3 19 2
Priyanka Pradhan 91
Anonymous Functions
• A lambda expression
returns a function
>>> f = lambda x,y : x + y
object >>> f(2,3)
• The body can only 5
be a simple >>> lst = ['one', lambda x : x * x, 3]
expression, not >>> lst[1](4)
complex statements 16
Priyanka Pradhan 92
Modules
Priyanka Pradhan 93