Python Programming
Language
By: Priyanka Pradhan
Priyanka Pradhan 1
Books include:
• Learning Python by Mark Lutz
• Python Essential Reference by David
Beazley
• Python Cookbook, ed. by Martelli,
Ravenscroft and Ascher
• (online at
http://code.activestate.com/recipes/langs/pyt
hon/)
• http://wiki.python.org/moin/PythonBooksPriyanka Pradhan 2
4 Major Versions of Python
• “Python” or “CPython” is written in C/C++
- Version 2.7 came out in mid-2010
- Version 3.1.2 came out in early 2010
• “Jython” is written in Java for the JVM
• “IronPython” is written in C# for the .Net
environment
Priyanka Pradhan 3
Contd…
• Created in 1989 by Guido Van Rossum
• Python 1.0 released in 1994
• Python 2.0 released in 2000
• Python 3.0 released in 2008
• Python 2.7 is the recommended version
• 3.0 adoption will take a few years
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
• Multi-purpose (Web, GUI, Scripting,
etc.)
• Object Oriented
• Interpreted
• Strongly typed and Dynamically typed
• Focus on readability and productivity
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
• Most languages don’t care about
indentation
• Most humans do
• We tend to group similar things together
Priyanka Pradhan 13
Hello World
>>> 'hello world!'
'hello world!'
•Open a terminal window and type “python”
•If on Windows open a Python IDE like IDLE
•At the prompt type ‘hello world!’
Priyanka Pradhan 14
Python Overview
• Programs are composed of modules
• Modules contain statements
• Statements contain expressions
• Expressions create and process objects
Priyanka Pradhan 15
The Python Interpreter
•Python is an interpreted
language
•The interpreter provides an
interactive environment to
play with the language
•Results of expressions are
printed on the screen
>>> 3 + 7
10
>>> 3 < 15
True
>>> 'print me'
'print me'
>>> print 'print me'
print me
>>>
Priyanka Pradhan 16
The print Statement
>>> print 'hello'
hello
>>> print 'hello', 'there'
hello there
•Elements separated by
commas print with a space
between them
•A comma at the end of the
statement (print ‘hello’,) will
not print a newline character
Priyanka Pradhan 17
Documentation
>>> 'this will print'
'this will print'
>>> #'this will not'
>>>
The ‘#’ starts a line comment
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
everything, including
functions and classes
(more on this later!)
• Data type is a property
of the object and not of
the variable
>>> x = 7
>>> x
7
>>> x = 'hello'
>>> x
'hello'
>>>
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
• concatenate with + or neighbours
– word = 'Help' + x
– word = 'Help' 'a'
• subscripting of strings
– 'Hello'[2]  'l'
– slice: 'Hello'[1:2]  'el'
– word[-1]  last character
– len(word)  5
– immutable: cannot assign to subscriptPriyanka Pradhan 22
Numbers: Integers
• Integer – the equivalent of
a C long
• Long Integer – an
unbounded integer value.
>>> 132224
132224
>>> 132323 ** 2
17509376329L
>>>
Priyanka Pradhan 23
Numbers: Floating Point
• int(x) converts x to an
integer
• float(x) converts x to a
floating point
• The interpreter shows
a lot of digits
>>> 1.23232
1.2323200000000001
>>> print 1.23232
1.23232
>>> 1.3E7
13000000.0
>>> int(2.0)
2
>>> float(2)
2.0
Priyanka Pradhan 24
Numbers: Complex
• Built into Python
• Same operations are
supported as integer and
float
>>> x = 3 + 2j
>>> y = -1j
>>> x + y
(3+1j)
>>> x * y
(2-3j)
Priyanka Pradhan 25
Numbers are immutable
>>> x = 4.5
>>> y = x
>>> y += 3
>>> x
4.5
>>> y
7.5
x 4.5
y
x 4.5
y 7.5
Priyanka Pradhan 26
String Literals
• Strings are immutable
• There is no char type like
in C++ or Java
• + is overloaded to do
concatenation
>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
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 longernthan the others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘ Priyanka Pradhan 28
Substrings and Methods
>>> s = '012345'
>>> s[3]
'3'
>>> s[1:4]
'123'
>>> s[2:]
'2345'
>>> s[:4]
'0123'
>>> s[-2]
'4'
• len(String) – returns the
number of characters in the
String
• str(Object) – returns a
String representation of the
Object
>>> len(x)
6
>>> str(10.3)
'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
• pass does nothing
• syntactic filler
while 1:
pass
Priyanka Pradhan 31
Operators
• Arithmetic
Priyanka Pradhan 32
String Manipulation
Priyanka Pradhan 33
Priyanka Pradhan 34
Logical Comparison
Identity Comparison
Priyanka Pradhan 35
Arithmetic Comparison
Priyanka Pradhan 36
Class Declaration
Priyanka Pradhan 37
Class Attributes
• Attributes assigned at class declaration
should always be immutable
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
types
• Lists are mutable
• Issues with shared
references and mutability
• Same subset operations as
Strings
>>> x = [1,'hello', (3 + 2j)]
>>> x
[1, 'hello', (3+2j)]
>>> x[2]
(3+2j)
>>> x[0:2]
[1, 'hello']
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
ith element to the
value a
• Since x and y point to
the same list object,
both are changed
• The method append
also modifies the list
>>> x = [1,2,3]
>>> y = x
>>> x[1] = 15
>>> x
[1, 15, 3]
>>> y
[1, 15, 3]
>>> x.append(12)
>>> y
[1, 15, 3, 12]
Priyanka Pradhan 48
Lists: Modifying Contents
• The method
append modifies
the list and returns
None
• List addition (+)
returns a new list
>>> x = [1,2,3]
>>> y = x
>>> z = x.append(12)
>>> z == None
True
>>> y
[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 = "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/FalseTrue/False
>>> "%s@brandeis.edu" % "clin"
'clin@brandeis.edu''clin@brandeis.edu'
>>> names = [“Ben", “Chen", “Yaqin"]
>>> ", ".join(names)
‘‘Ben, Chen, Yaqin‘Ben, Chen, Yaqin‘
>>> “chen".upper()
‘‘CHEN'CHEN'
Priyanka Pradhan 54
“” is for special characters
n -> newline
t -> tab
 -> backslash
...
But Windows uses backslash for directories!
filename = "M:nickel_projectreactive.smi" # DANGER!
filename = "M:nickel_projectreactive.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
format to make a tuple with
one element:
‘,’ is needed to differentiate
from the mathematical
expression (2)
>>> x = (1,2,3)
>>> x[1:]
(2, 3)
>>> y = (2,)
>>> y
(2,)
>>>
Priyanka Pradhan 56
Tuples and sequences
• lists, strings, tuples: examples of sequence
type
• tuple = values separated by commas
>>> t = 123, 543, 'bar'
>>> t[0]
123
>>> t
(123, 543, 'bar')
Priyanka Pradhan 57
Contd…
• Tuples may be nested
>>> u = t, (1,2)
>>> u
((123, 542, 'bar'), (1,2))
• Empty tuples: ()
>>> empty = ()
>>> len(empty)
0 Priyanka Pradhan 58
Dictionaries
• A set of key-value pairs
• Dictionaries are mutable
>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
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
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
• Entries can be changed by assigning to that entry
• Assigning to a key that does not exist adds an entry
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
function will
copy a list
• The dictionary
has a method
called copy
>>> l1 = [1]
>>> l2 = list(l1)
>>> l1[0] = 22
>>> l1
[22]
>>> l2
[1]
>>> d = {1 : 10}
>>> d2 = d.copy()
>>> d[1] = 22
>>> d
{1: 22}
>>> d2
{1: 10}
Priyanka Pradhan 63
Dictionary Methods
Priyanka Pradhan 64
Data Type Summary
• Lists, Tuples, and Dictionaries can store any type
(including other lists, tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• All variables are references
Priyanka Pradhan 65
Contd…
• Integers: 2323, 3234L
• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
Priyanka Pradhan 66
Modules
• collection of functions and variables,
typically in scripts
• definitions can be imported
• file name is module name + .py
• e.g., create module fibo.py
def fib(n): # write Fib. series up to n
...
def fib2(n): # return Fib. series up to nPriyanka Pradhan 67
Contd…
• function definition + executable statements
• executed only when module is imported
• modules have private symbol tables
• avoids name clash for global variables
• accessible as module.globalname
• can import into name space:
>>> from fibo import fib, fib2
>>> fib(500)
• can import all names defined by module:
>>> from fibo import *
Priyanka Pradhan 68
Input
• The raw_input(string) method returns a line of
user input as a string
• The parameter is used as a prompt
• The string can be converted by using the
conversion methods int(string), float(string), etc.
Priyanka Pradhan 69
Input: Example
print “enter your name?"
name = raw_input("> ")
print "When were you born?"
birthyear = int(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 31 years old!Priyanka Pradhan 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
short circuit
• and and or return one of the
elements in the expression
• Note that when None is returned
the interpreter does not print
anything
>>> True and False
False
>>> False or True
True
>>> 7 and 14
14
>>> None and 2
>>> 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 :
y = x + 15
elif x <= 30 :
y = x + 30
else :
y = x
print ‘y = ‘,
print math.sin(y)
In file ifstatement.py
>>> import ifstatement
y = 0.999911860107
>>>
In interpreter
Priyanka Pradhan 74
While Loops
x = 1
while x < 10 :
print x
x = x + 1
>>> import whileloop
1
2
3
4
5
6
7
8
9
>>>
In whileloop.py
In interpreter
Priyanka Pradhan 75
Loop Control Statements
break Jumps out of the closest
enclosing loop
continue Jumps to the top of the closest
enclosing loop
pass Does nothing, empty statement
placeholder
Priyanka Pradhan 76
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x = 1
while x < 3 :
print x
x = x + 1
else:
print 'hello'
~: python whileelse.py
1
2
hello
Run from the command line
In whileelse.py
Priyanka Pradhan 77
The Loop Else Clause
x = 1
while x < 5 :
print x
x = x + 1
break
else :
print 'i got here'
~: python whileelse2.py
1
whileelse2.py
Priyanka Pradhan 78
For Loops
~: python forloop1.py
1
7
13
2
for x in [1,7,13,2] :
print xforloop1.py
~: python forloop2.py
0
1
2
3
4
for x in range(5) :
print xforloop2.py
range(N) generates a list of numbers [0,1, …, n-1]Priyanka Pradhan 79
For Loops
• For loops also may have the optional else clause
for x in range(5):
print x
break
else :
print 'i got here'
~: python elseforloop.py
1
elseforloop.py
Priyanka Pradhan 80
Function Basics
def max(x,y) :
if x < y :
return x
else :
return y
>>> import functionbasics
>>> max(3,5)
5
>>> max('hello', 'there')
'there'
>>> max(3, 'hello')
'hello'
functionbasics.py
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
• Functions are objects
• The same reference
rules hold for them as
for other objects
>>> x = 10
>>> x
10
>>> def x () :
... print 'hello'
>>> x
<function x at 0x619f0>
>>> x()
hello
>>> x = 'blah'
>>> x
'blah'
Priyanka Pradhan 83
Functions as Parameters
def foo(f, a) :
return f(a)
def bar(x) :
return x * x
>>> from funcasparam import *
>>> foo(bar, 3)
9
Note that the function foo takes two
parameters and applies the first as a
function with the second as its
parameter
funcasparam.py
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.
def double(x):
return 2*x
>>> from highorder import *
>>> lst = range(10)
>>> lst
[0,1,2,3,4,5,6,7,8,9]
>>> map(double,lst)
[0,2,4,6,8,10,12,14,16,18]
highorder.py
Priyanka Pradhan 85
Higher-Order Functions
filter(boolfunc,seq) – returns a sequence containing all those items
in seq for which boolfunc is True.
def even(x):
return ((x%2 == 0)
>>> from highorder import *
>>> lst = range(10)
>>> lst
[0,1,2,3,4,5,6,7,8,9]
>>> filter(even,lst)
[0,2,4,6,8]
highorder.py
Priyanka Pradhan 86
Higher-Order Functions
reduce(func,seq) – applies func to the items of seq, from left to
right, two-at-time, to reduce the seq to a single value.
def plus(x,y):
return (x + y)
>>> from highorder import *
>>> lst = [‘h’,’e’,’l’,’l’,’o’]
>>> reduce(plus,lst)
‘hello’
highorder.py
Priyanka Pradhan 87
Functions Inside Functions
• Since they are like any other object, you can have
functions inside functions
def foo (x,y) :
def bar (z) :
return z * 2
return bar(x) + y
>>> from funcinfunc import *
>>> foo(2,3)
7
funcinfunc.py
Priyanka Pradhan 88
Functions Returning Functions
def foo (x) :
def bar(y) :
return x + y
return bar
# main
f = foo(3)
print f
print f(2)
~: python funcreturnfunc.py
<function bar at 0x612b0>
5
funcreturnfunc.py
Priyanka Pradhan 89
Parameters: Defaults
• Parameters can be
assigned default
values
• They are overridden if
a parameter is given
for them
• The type of the default
doesn’t limit the type
of a parameter
>>> def foo(x = 3) :
... print x
...
>>> foo()
3
>>> foo(10)
10
>>> foo('hello')
hello
Priyanka Pradhan 90
Parameters: Named
• Call by name
• Any positional
arguments must
come before
named ones in a
call
>>> def foo (a,b,c) :
... print a, b, c
...
>>> foo(c = 10, a = 2, b = 14)
2 14 10
>>> foo(3, c = 2, b = 19)
3 19 2
Priyanka Pradhan 91
Anonymous Functions
• A lambda expression
returns a function
object
• The body can only
be a simple
expression, not
complex statements
>>> f = lambda x,y : x + y
>>> f(2,3)
5
>>> lst = ['one', lambda x : x * x, 3]
>>> lst[1](4)
16
Priyanka Pradhan 92
Modules
• The highest level structure of Python
• Each file with the py suffix is a module
• Each module has its own namespace
Priyanka Pradhan 93

More Related Content

PDF
Python made easy
PPTX
Python Tutorial Part 1
PPTX
Introduction python
PPTX
Python ppt
PPT
Python ppt
PPTX
PYTHON FEATURES.pptx
PPTX
Python presentation by Monu Sharma
PPTX
Python Programming Language
Python made easy
Python Tutorial Part 1
Introduction python
Python ppt
Python ppt
PYTHON FEATURES.pptx
Python presentation by Monu Sharma
Python Programming Language

What's hot (20)

PDF
Strings in python
PDF
Python basic
PPTX
Chapter 03 python libraries
PPTX
Python in 30 minutes!
PDF
Basic Concepts in Python
PPTX
List in Python
PPTX
Python basics
PPTX
Two dimensional arrays
PDF
Variables & Data Types In Python | Edureka
PPTX
Introduction to python for Beginners
PPTX
Chapter 05 classes and objects
PPTX
Data types in python
PPTX
Linux commands
PPT
Python Programming Language
PPTX
Introduction to python
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
PDF
Arrays in python
PPTX
File Handling Python
PDF
Python file handling
Strings in python
Python basic
Chapter 03 python libraries
Python in 30 minutes!
Basic Concepts in Python
List in Python
Python basics
Two dimensional arrays
Variables & Data Types In Python | Edureka
Introduction to python for Beginners
Chapter 05 classes and objects
Data types in python
Linux commands
Python Programming Language
Introduction to python
Python 101: Python for Absolute Beginners (PyTexas 2014)
Arrays in python
File Handling Python
Python file handling
Ad

Similar to programming with python ppt (20)

PPT
Python tutorialfeb152012
PPT
Python basics to advanced in on ppt is available
PPTX
Python Scipy Numpy
PPT
Python - Module 1.ppt
PPTX
Introduction to Programming.pptx ok ok ok
PPT
Introduction to Python For Diploma Students
PPTX
Introduction to Python Programming Language
PPTX
Exploring Data Science Using Python Tools
PDF
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
PDF
Python Basics
PPTX
Python Workshop
PPT
python introduction all the students.ppt
PPTX
funadamentals of python programming language (right from scratch)
PDF
Learn Python 3 for absolute beginners
PPTX
Introduction to python programming ( part-1)
PDF
ppt_pspp.pdf
PPTX
unit (1)INTRODUCTION TO PYTHON course.pptx
PDF
Computer Related material named Phython ok
PDF
Introduction to python
PPTX
Introduction to Python Programming .pptx
Python tutorialfeb152012
Python basics to advanced in on ppt is available
Python Scipy Numpy
Python - Module 1.ppt
Introduction to Programming.pptx ok ok ok
Introduction to Python For Diploma Students
Introduction to Python Programming Language
Exploring Data Science Using Python Tools
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
Python Basics
Python Workshop
python introduction all the students.ppt
funadamentals of python programming language (right from scratch)
Learn Python 3 for absolute beginners
Introduction to python programming ( part-1)
ppt_pspp.pdf
unit (1)INTRODUCTION TO PYTHON course.pptx
Computer Related material named Phython ok
Introduction to python
Introduction to Python Programming .pptx
Ad

More from Priyanka Pradhan (19)

PPTX
Tomato disease detection using deep learning convolutional neural network
PPTX
PPTX
PPTX
Javascript
PPTX
Core Java
PPTX
Image Processing Based Signature Recognition and Verification Technique Using...
PPTX
GrayBox Testing and Crud Testing By: Er. Priyanka Pradhan
PPTX
The agile requirements refinery(SRUM) by: Priyanka Pradhan
ODP
Social tagging and its trend
PPTX
Behavioral pattern By:-Priyanka Pradhan
PPTX
software product and its characteristics
PPTX
EDI(ELECTRONIC DATA INTERCHANGE)
PPT
collaborative tagging :-by Er. Priyanka Pradhan
PPT
Deploying java beans in jsp
PPTX
SOFTWARE PROCESS MONITORING AND AUDIT
PPTX
s/w metrics monitoring and control
Tomato disease detection using deep learning convolutional neural network
Javascript
Core Java
Image Processing Based Signature Recognition and Verification Technique Using...
GrayBox Testing and Crud Testing By: Er. Priyanka Pradhan
The agile requirements refinery(SRUM) by: Priyanka Pradhan
Social tagging and its trend
Behavioral pattern By:-Priyanka Pradhan
software product and its characteristics
EDI(ELECTRONIC DATA INTERCHANGE)
collaborative tagging :-by Er. Priyanka Pradhan
Deploying java beans in jsp
SOFTWARE PROCESS MONITORING AND AUDIT
s/w metrics monitoring and control

Recently uploaded (20)

PDF
Ensemble model-based arrhythmia classification with local interpretable model...
PDF
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
PDF
Early detection and classification of bone marrow changes in lumbar vertebrae...
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Dell Pro Micro: Speed customer interactions, patient processing, and learning...
PDF
SaaS reusability assessment using machine learning techniques
PDF
Data Virtualization in Action: Scaling APIs and Apps with FME
PDF
Introduction to MCP and A2A Protocols: Enabling Agent Communication
PPTX
SGT Report The Beast Plan and Cyberphysical Systems of Control
PDF
Human Computer Interaction Miterm Lesson
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
PDF
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
PPTX
Build automations faster and more reliably with UiPath ScreenPlay
PDF
4 layer Arch & Reference Arch of IoT.pdf
PDF
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
PDF
Examining Bias in AI Generated News Content.pdf
PDF
The AI Revolution in Customer Service - 2025
Ensemble model-based arrhythmia classification with local interpretable model...
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
Early detection and classification of bone marrow changes in lumbar vertebrae...
Presentation - Principles of Instructional Design.pptx
Dell Pro Micro: Speed customer interactions, patient processing, and learning...
SaaS reusability assessment using machine learning techniques
Data Virtualization in Action: Scaling APIs and Apps with FME
Introduction to MCP and A2A Protocols: Enabling Agent Communication
SGT Report The Beast Plan and Cyberphysical Systems of Control
Human Computer Interaction Miterm Lesson
Rapid Prototyping: A lecture on prototyping techniques for interface design
NewMind AI Weekly Chronicles – August ’25 Week IV
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
Build automations faster and more reliably with UiPath ScreenPlay
4 layer Arch & Reference Arch of IoT.pdf
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
Examining Bias in AI Generated News Content.pdf
The AI Revolution in Customer Service - 2025

programming with python ppt

  • 1. Python Programming Language By: Priyanka Pradhan Priyanka Pradhan 1
  • 2. Books include: • Learning Python by Mark Lutz • Python Essential Reference by David Beazley • Python Cookbook, ed. by Martelli, Ravenscroft and Ascher • (online at http://code.activestate.com/recipes/langs/pyt hon/) • http://wiki.python.org/moin/PythonBooksPriyanka Pradhan 2
  • 3. 4 Major Versions of Python • “Python” or “CPython” is written in C/C++ - Version 2.7 came out in mid-2010 - Version 3.1.2 came out in early 2010 • “Jython” is written in Java for the JVM • “IronPython” is written in C# for the .Net environment Priyanka Pradhan 3
  • 4. Contd… • Created in 1989 by Guido Van Rossum • Python 1.0 released in 1994 • Python 2.0 released in 2000 • Python 3.0 released in 2008 • Python 2.7 is the recommended version • 3.0 adoption will take a few years Priyanka Pradhan 4
  • 5. 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
  • 6. Web Frameworks • Django • Flask • Pylons • TurboGears • Zope • Grok Priyanka Pradhan 6
  • 7. Introduction • Multi-purpose (Web, GUI, Scripting, etc.) • Object Oriented • Interpreted • Strongly typed and Dynamically typed • Focus on readability and productivity Priyanka Pradhan 7
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. Who Uses Python • Google • PBS • NASA • Library of Congress • the ONION • ...the list goes on... Priyanka Pradhan 11
  • 12. 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
  • 13. Indentation • Most languages don’t care about indentation • Most humans do • We tend to group similar things together Priyanka Pradhan 13
  • 14. Hello World >>> 'hello world!' 'hello world!' •Open a terminal window and type “python” •If on Windows open a Python IDE like IDLE •At the prompt type ‘hello world!’ Priyanka Pradhan 14
  • 15. Python Overview • Programs are composed of modules • Modules contain statements • Statements contain expressions • Expressions create and process objects Priyanka Pradhan 15
  • 16. The Python Interpreter •Python is an interpreted language •The interpreter provides an interactive environment to play with the language •Results of expressions are printed on the screen >>> 3 + 7 10 >>> 3 < 15 True >>> 'print me' 'print me' >>> print 'print me' print me >>> Priyanka Pradhan 16
  • 17. The print Statement >>> print 'hello' hello >>> print 'hello', 'there' hello there •Elements separated by commas print with a space between them •A comma at the end of the statement (print ‘hello’,) will not print a newline character Priyanka Pradhan 17
  • 18. Documentation >>> 'this will print' 'this will print' >>> #'this will not' >>> The ‘#’ starts a line comment Priyanka Pradhan 18
  • 19. 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
  • 20. Everything is an object • Everything means everything, including functions and classes (more on this later!) • Data type is a property of the object and not of the variable >>> x = 7 >>> x 7 >>> x = 'hello' >>> x 'hello' >>> Priyanka Pradhan 20
  • 21. 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
  • 22. String operations • concatenate with + or neighbours – word = 'Help' + x – word = 'Help' 'a' • subscripting of strings – 'Hello'[2]  'l' – slice: 'Hello'[1:2]  'el' – word[-1]  last character – len(word)  5 – immutable: cannot assign to subscriptPriyanka Pradhan 22
  • 23. Numbers: Integers • Integer – the equivalent of a C long • Long Integer – an unbounded integer value. >>> 132224 132224 >>> 132323 ** 2 17509376329L >>> Priyanka Pradhan 23
  • 24. Numbers: Floating Point • int(x) converts x to an integer • float(x) converts x to a floating point • The interpreter shows a lot of digits >>> 1.23232 1.2323200000000001 >>> print 1.23232 1.23232 >>> 1.3E7 13000000.0 >>> int(2.0) 2 >>> float(2) 2.0 Priyanka Pradhan 24
  • 25. Numbers: Complex • Built into Python • Same operations are supported as integer and float >>> x = 3 + 2j >>> y = -1j >>> x + y (3+1j) >>> x * y (2-3j) Priyanka Pradhan 25
  • 26. Numbers are immutable >>> x = 4.5 >>> y = x >>> y += 3 >>> x 4.5 >>> y 7.5 x 4.5 y x 4.5 y 7.5 Priyanka Pradhan 26
  • 27. String Literals • Strings are immutable • There is no char type like in C++ or Java • + is overloaded to do concatenation >>> x = 'hello' >>> x = x + ' there' >>> x 'hello there' Priyanka Pradhan 27
  • 28. 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 longernthan the others :)‘ >>> print s And me too! though I am much longer than the others :)‘ Priyanka Pradhan 28
  • 29. Substrings and Methods >>> s = '012345' >>> s[3] '3' >>> s[1:4] '123' >>> s[2:] '2345' >>> s[:4] '0123' >>> s[-2] '4' • len(String) – returns the number of characters in the String • str(Object) – returns a String representation of the Object >>> len(x) 6 >>> str(10.3) '10.3' Priyanka Pradhan 29
  • 30. 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
  • 31. Do nothing • pass does nothing • syntactic filler while 1: pass Priyanka Pradhan 31
  • 38. Class Attributes • Attributes assigned at class declaration should always be immutable Priyanka Pradhan 38
  • 40. Class Instantiation & Attribute Access Priyanka Pradhan 40
  • 44. Lists • Ordered collection of data • Data can be of different types • Lists are mutable • Issues with shared references and mutability • Same subset operations as Strings >>> x = [1,'hello', (3 + 2j)] >>> x [1, 'hello', (3+2j)] >>> x[2] (3+2j) >>> x[0:2] [1, 'hello'] Priyanka Pradhan 44
  • 45. 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
  • 46. 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
  • 47. Contd… • count(x) – how many times x appears in list • sort() – sort items in place • reverse() – reverse list Priyanka Pradhan 47
  • 48. Lists: Modifying Content • x[i] = a reassigns the ith element to the value a • Since x and y point to the same list object, both are changed • The method append also modifies the list >>> x = [1,2,3] >>> y = x >>> x[1] = 15 >>> x [1, 15, 3] >>> y [1, 15, 3] >>> x.append(12) >>> y [1, 15, 3, 12] Priyanka Pradhan 48
  • 49. Lists: Modifying Contents • The method append modifies the list and returns None • List addition (+) returns a new list >>> x = [1,2,3] >>> y = x >>> z = x.append(12) >>> z == None True >>> y [1, 2, 3, 12] >>> x = x + [9,10] >>> x [1, 2, 3, 12, 9, 10] >>> y [1, 2, 3, 12] >>>Priyanka Pradhan 49
  • 50. 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
  • 51. String Methods: find, split smiles = "C(=N)(N)N.C(=O)(O)O"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
  • 52. 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
  • 53. 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
  • 54. More String methods email.startswith(“c") endswith(“u”) True/FalseTrue/False >>> "%[email protected]" % "clin" '[email protected]''[email protected]' >>> names = [“Ben", “Chen", “Yaqin"] >>> ", ".join(names) ‘‘Ben, Chen, Yaqin‘Ben, Chen, Yaqin‘ >>> “chen".upper() ‘‘CHEN'CHEN' Priyanka Pradhan 54
  • 55. “” is for special characters n -> newline t -> tab -> backslash ... But Windows uses backslash for directories! filename = "M:nickel_projectreactive.smi" # DANGER! filename = "M:nickel_projectreactive.smi" # Better! filename = "M:/nickel_project/reactive.smi" # Usually works Priyanka Pradhan 55
  • 56. Tuples • Tuples are immutable versions of lists • One strange point is the format to make a tuple with one element: ‘,’ is needed to differentiate from the mathematical expression (2) >>> x = (1,2,3) >>> x[1:] (2, 3) >>> y = (2,) >>> y (2,) >>> Priyanka Pradhan 56
  • 57. Tuples and sequences • lists, strings, tuples: examples of sequence type • tuple = values separated by commas >>> t = 123, 543, 'bar' >>> t[0] 123 >>> t (123, 543, 'bar') Priyanka Pradhan 57
  • 58. Contd… • Tuples may be nested >>> u = t, (1,2) >>> u ((123, 542, 'bar'), (1,2)) • Empty tuples: () >>> empty = () >>> len(empty) 0 Priyanka Pradhan 58
  • 59. Dictionaries • A set of key-value pairs • Dictionaries are mutable >>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]} >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['blah'] [1, 2, 3] Priyanka Pradhan 59
  • 60. 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
  • 61. Dictionaries: Add/Modify >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['two'] = 99 >>> d {1: 'hello', 'two': 99, 'blah': [1, 2, 3]} >>> d[7] = 'new entry' >>> d {1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]} • Entries can be changed by assigning to that entry • Assigning to a key that does not exist adds an entry Priyanka Pradhan 61
  • 62. 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
  • 63. Copying Dictionaries and Lists • The built-in list function will copy a list • The dictionary has a method called copy >>> l1 = [1] >>> l2 = list(l1) >>> l1[0] = 22 >>> l1 [22] >>> l2 [1] >>> d = {1 : 10} >>> d2 = d.copy() >>> d[1] = 22 >>> d {1: 22} >>> d2 {1: 10} Priyanka Pradhan 63
  • 65. Data Type Summary • Lists, Tuples, and Dictionaries can store any type (including other lists, tuples, and dictionaries!) • Only lists and dictionaries are mutable • All variables are references Priyanka Pradhan 65
  • 66. Contd… • Integers: 2323, 3234L • Floating Point: 32.3, 3.1E2 • Complex: 3 + 2j, 1j • Lists: l = [ 1,2,3] • Tuples: t = (1,2,3) • Dictionaries: d = {‘hello’ : ‘there’, 2 : 15} Priyanka Pradhan 66
  • 67. Modules • collection of functions and variables, typically in scripts • definitions can be imported • file name is module name + .py • e.g., create module fibo.py def fib(n): # write Fib. series up to n ... def fib2(n): # return Fib. series up to nPriyanka Pradhan 67
  • 68. Contd… • function definition + executable statements • executed only when module is imported • modules have private symbol tables • avoids name clash for global variables • accessible as module.globalname • can import into name space: >>> from fibo import fib, fib2 >>> fib(500) • can import all names defined by module: >>> from fibo import * Priyanka Pradhan 68
  • 69. Input • The raw_input(string) method returns a line of user input as a string • The parameter is used as a prompt • The string can be converted by using the conversion methods int(string), float(string), etc. Priyanka Pradhan 69
  • 70. Input: Example print “enter your name?" name = raw_input("> ") print "When were you born?" birthyear = int(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 31 years old!Priyanka Pradhan 70
  • 71. Booleans • 0 and None are false • Everything else is true • True and False are aliases for 1 and 0 respectively Priyanka Pradhan 71
  • 72. Boolean Expressions • Compound boolean expressions short circuit • and and or return one of the elements in the expression • Note that when None is returned the interpreter does not print anything >>> True and False False >>> False or True True >>> 7 and 14 14 >>> None and 2 >>> None or 2 2 Priyanka Pradhan 72
  • 73. 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
  • 74. If Statements import math x = 30 if x <= 15 : y = x + 15 elif x <= 30 : y = x + 30 else : y = x print ‘y = ‘, print math.sin(y) In file ifstatement.py >>> import ifstatement y = 0.999911860107 >>> In interpreter Priyanka Pradhan 74
  • 75. While Loops x = 1 while x < 10 : print x x = x + 1 >>> import whileloop 1 2 3 4 5 6 7 8 9 >>> In whileloop.py In interpreter Priyanka Pradhan 75
  • 76. Loop Control Statements break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop pass Does nothing, empty statement placeholder Priyanka Pradhan 76
  • 77. The Loop Else Clause • The optional else clause runs only if the loop exits normally (not by break) x = 1 while x < 3 : print x x = x + 1 else: print 'hello' ~: python whileelse.py 1 2 hello Run from the command line In whileelse.py Priyanka Pradhan 77
  • 78. The Loop Else Clause x = 1 while x < 5 : print x x = x + 1 break else : print 'i got here' ~: python whileelse2.py 1 whileelse2.py Priyanka Pradhan 78
  • 79. For Loops ~: python forloop1.py 1 7 13 2 for x in [1,7,13,2] : print xforloop1.py ~: python forloop2.py 0 1 2 3 4 for x in range(5) : print xforloop2.py range(N) generates a list of numbers [0,1, …, n-1]Priyanka Pradhan 79
  • 80. For Loops • For loops also may have the optional else clause for x in range(5): print x break else : print 'i got here' ~: python elseforloop.py 1 elseforloop.py Priyanka Pradhan 80
  • 81. Function Basics def max(x,y) : if x < y : return x else : return y >>> import functionbasics >>> max(3,5) 5 >>> max('hello', 'there') 'there' >>> max(3, 'hello') 'hello' functionbasics.py Priyanka Pradhan 81
  • 82. 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
  • 83. Function names are like any variable • Functions are objects • The same reference rules hold for them as for other objects >>> x = 10 >>> x 10 >>> def x () : ... print 'hello' >>> x <function x at 0x619f0> >>> x() hello >>> x = 'blah' >>> x 'blah' Priyanka Pradhan 83
  • 84. Functions as Parameters def foo(f, a) : return f(a) def bar(x) : return x * x >>> from funcasparam import * >>> foo(bar, 3) 9 Note that the function foo takes two parameters and applies the first as a function with the second as its parameter funcasparam.py Priyanka Pradhan 84
  • 85. Higher-Order Functions map(func,seq) – for all i, applies func(seq[i]) and returns the corresponding sequence of the calculated results. def double(x): return 2*x >>> from highorder import * >>> lst = range(10) >>> lst [0,1,2,3,4,5,6,7,8,9] >>> map(double,lst) [0,2,4,6,8,10,12,14,16,18] highorder.py Priyanka Pradhan 85
  • 86. Higher-Order Functions filter(boolfunc,seq) – returns a sequence containing all those items in seq for which boolfunc is True. def even(x): return ((x%2 == 0) >>> from highorder import * >>> lst = range(10) >>> lst [0,1,2,3,4,5,6,7,8,9] >>> filter(even,lst) [0,2,4,6,8] highorder.py Priyanka Pradhan 86
  • 87. Higher-Order Functions reduce(func,seq) – applies func to the items of seq, from left to right, two-at-time, to reduce the seq to a single value. def plus(x,y): return (x + y) >>> from highorder import * >>> lst = [‘h’,’e’,’l’,’l’,’o’] >>> reduce(plus,lst) ‘hello’ highorder.py Priyanka Pradhan 87
  • 88. Functions Inside Functions • Since they are like any other object, you can have functions inside functions def foo (x,y) : def bar (z) : return z * 2 return bar(x) + y >>> from funcinfunc import * >>> foo(2,3) 7 funcinfunc.py Priyanka Pradhan 88
  • 89. Functions Returning Functions def foo (x) : def bar(y) : return x + y return bar # main f = foo(3) print f print f(2) ~: python funcreturnfunc.py <function bar at 0x612b0> 5 funcreturnfunc.py Priyanka Pradhan 89
  • 90. Parameters: Defaults • Parameters can be assigned default values • They are overridden if a parameter is given for them • The type of the default doesn’t limit the type of a parameter >>> def foo(x = 3) : ... print x ... >>> foo() 3 >>> foo(10) 10 >>> foo('hello') hello Priyanka Pradhan 90
  • 91. Parameters: Named • Call by name • Any positional arguments must come before named ones in a call >>> def foo (a,b,c) : ... print a, b, c ... >>> foo(c = 10, a = 2, b = 14) 2 14 10 >>> foo(3, c = 2, b = 19) 3 19 2 Priyanka Pradhan 91
  • 92. Anonymous Functions • A lambda expression returns a function object • The body can only be a simple expression, not complex statements >>> f = lambda x,y : x + y >>> f(2,3) 5 >>> lst = ['one', lambda x : x * x, 3] >>> lst[1](4) 16 Priyanka Pradhan 92
  • 93. Modules • The highest level structure of Python • Each file with the py suffix is a module • Each module has its own namespace Priyanka Pradhan 93

Editor's Notes

  • #9: fast development object-oriented programming code structuring and reuse, C++ embedding and extending in C mixed language systems classes, modules, exceptions &amp;quot;programming-in-the-large&amp;quot; support dynamic loading of C modules simplified extensions, smaller binaries dynamic reloading of C modules programs can be modified without stopping fast development object-oriented programming code structuring and reuse, C++ embedding and extending in C mixed language systems classes, modules, exceptions &amp;quot;programming-in-the-large&amp;quot; support dynamic loading of C modules simplified extensions, smaller binaries dynamic reloading of C modules programs can be modified without stopping