0% found this document useful (0 votes)
2 views16 pages

Lecture02.Python.part02 Functions

This document provides an overview of Python programming concepts covered in Lecture 02 of EEB435, including dictionaries, functions, logical expressions, and flow control. Key topics include creating and accessing dictionaries, defining functions, using logical expressions, and implementing flow control structures such as if statements and loops. The document also discusses advanced features like list comprehensions and higher-order functions.

Uploaded by

leano.loeto
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Lecture02.Python.part02 Functions

This document provides an overview of Python programming concepts covered in Lecture 02 of EEB435, including dictionaries, functions, logical expressions, and flow control. Key topics include creating and accessing dictionaries, defining functions, using logical expressions, and implementing flow control structures such as if statements and loops. The document also discusses advanced features like list comprehensions and higher-order functions.

Uploaded by

leano.loeto
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Overview

Lecture 02:
EEB435: Computer Programming II  Dictionaries
 Functions
Introduction to Python Part 2  Logical expressions
 Flow of control
 Comprehensions
Dr Ditshego  For loops
 More on functions
Adapted from  Assignment and containers
Upenn cis391 slides and
other sources  Strings

Dictionaries: A Mapping type Creating & accessing dictionaries


 Dictionaries store a mapping between a set of >>> d = {‘user’:‘bua’, ‘pswd’:1234}
keys and a set of values >>> d[‘user’]
• Keys can be any immutable type. ‘bua’
• Values can be any type >>> d[‘pswd’]
• A single dictionary can store values of 123
different types >>> d[‘bua’]
Traceback (innermost last):
 You can define, modify, view, lookup or delete
File ‘<interactive input>’ line 1, in
the key-value pairs in the dictionary
?
 Python’s dictionaries are also known as hash KeyError: bua
tables and associative arrays

1
Updating Dictionaries Removing dictionary entries
>>> d = {‘user’:‘bozo’, ‘pswd’:1234} >>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
>>> d[‘user’] = ‘clown’ >>> del d[‘user’] # Remove one.
>>> d >>> d
{‘user’:‘clown’, ‘pswd’:1234}
{‘p’:1234, ‘i’:34}
 Keys must be unique
>>> [Link]() # Remove all.
 Assigning to an existing key replaces its value
>>> d
>>> d[‘id’] = 45
>>> d {}
{‘user’:‘clown’, ‘id’:45, ‘pswd’:1234}
>>> a=[1,2]
 Dictionaries are unordered >>> del a[1] # del works on lists, too
• New entries can appear anywhere in output >>> a
 Dictionaries work by hashing [1]

Useful Accessor Methods Why must keys be immutable?


 The keys used in a dictionary must be
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
immutable objects?
>>> name1, name2 = 'john', ['bob', 'marley']
>>> [Link]() # List of keys, VERY useful
>>> fav = name2
[‘user’, ‘p’, ‘i’]
>>> d = {name1: 'alive', name2: 'dead'}
Traceback (most recent call last):
>>> [Link]() # List of values File "<stdin>", line 1, in <module>
[‘bozo’, 1234, 34] TypeError: list objects are unhashable

>>> [Link]() # List of item tuples


 Why is this?
[(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]  Suppose we could index a value for name2
 and then did fav[0] = “Bobby”
 Could we find d[name2] or d[fav] or …?

2
Defining Functions
Function definition begins with “def.” Function name and its arguments.

Functions in Python def get_final_answer(filename):


“““Documentation String”””
line1
line2 Colon.
return total_counter

The indentation matters…


First line with less
indentation is considered to be The keyword ‘return’ indicates the
outside of the function definition. value to be sent back to the caller.

No header file or declaration of types of function or


arguments

Python and Types Calling a Function

 Dynamic typing: Python determines the data  The syntax for a function call is:
>>> def myfun(x, y):
types of variable bindings in a program
return x * y
automatically >>> myfun(3, 4)
 Strong typing: But Python’s not casual about 12
types, it enforces the types of objects  Parameters in Python are Call by Assignment
 For example, you can’t just append an integer • Old values for the variables that are parameter
to a string, but must first convert it to a string names are hidden, and these variables are
x = “the answer is ” # x bound to a string
simply made to refer to the new values
y = 23 # y bound to an integer. • All assignment in Python, including binding
function parameters, uses reference semantics.
print x + y # Python will complain!

3
Functions without returns Function overloading? No.
 All functions in Python have a return value,
even if no return line inside the code  There is no function overloading in Python
 Functions without a return return the special • Unlike C++, a Python function is specified by
value None its name alone
• None is a special constant in the language The number, order, names, or types of its
• None is used like NULL, void, or nil in other arguments cannot be used to distinguish between
two functions with the same name
languages
• None is also logically equivalent to False • Two different functions can’t have the same
• The interpreter doesn’t print None name, even if they have different arguments
 But: see operator overloading in later slides
(Note: van Rossum playing with function overloading for the future)

Default Values for Arguments Keyword Arguments


 You can provide default values for a function’s  You can call a function with some or all of its
arguments arguments out of order as long as you specify
 These arguments are optional when the their names
function is called  You can also just use keywords for a final
subset of the arguments.
>>> def myfun(b, c=3, d=“hello”): >>> def myfun(a, b, c):
return b + c return a-b
>>> myfun(5,3,”hello”) >>> myfun(2, 1, 43)
>>> myfun(5,3) 1
>>> myfun(5) >>> myfun(c=43, b=1, a=2)
1
All of the above function calls return 8 >>> myfun(2, c=43, b=1)
1

4
Functions are first-class objects Lambda Notation
Functions can be used as any other datatype, eg:
• Arguments to function  Python uses a lambda notation to create
• Return values of functions anonymous functions
>>> applier(lambda z: z * 4, 7)
• Assigned to variables
• Parts of tuples, lists, etc 28

>>> def square(x):


return x*x  Python supports functional programming
>>> def applier(q, x): idioms, including closures and continuations
return q(x)
>>> applier(square, 7)
49

Lambda Notation Example: composition


>>> def square(x):
Be careful with the syntax
return x*x
>>> f = lambda x,y : 2 * x + y
>>> f >>> def twice(f):
<function <lambda> at 0x87d30> return lambda x: f(f(x))
>>> f(3, 4) >>> twice
10 <function twice at 0x87db0>
>>> v = lambda x: x*x(100)
>>> quad = twice(square)
>>> v
<function <lambda> at 0x87df0>
>>> quad
>>> v = (lambda x: x*x)(100) <function <lambda> at 0x87d30>
>>> v >>> quad(5)
10000 625

5
Example: closure
>>> def counter(start=0, step=1):
x = [start]
def _inc():
x[0] += step
Logical Expressions
return x[0]
return _inc
>>> c1 = counter()
>>> c2 = counter(100, -10)
>>> c1()
1
>>> c2()
90

True and False Boolean Logic Expressions


 True and False are constants in Python.  You can also combine Boolean
 Other values equivalent to True and False: expressions.
• False: zero, None, empty container or • True if a is True and b is True: a and b
object • True if a is True or b is True: a or b
• True: non-zero numbers, non-empty • True if a is False: not a
objects
 Use parentheses as needed to
 Comparison operators: ==, !=, <, <=, etc. disambiguate complex Boolean
• X and Y have same value: X == Y expressions.
• Compare with X is Y :
—X and Y are two variables that refer to
the identical same object.

6
Special Properties of and & or The “and-or” Trick
 Actually and and or don’t return True or False  An old deprecated trick to implement a simple
but value of one of their sub-expressions, conditional
which may be a non-Boolean value result = test and expr1 or expr2
 X and Y and Z • When test is True, result is assigned expr1
• If all are true, returns value of Z • When test is False, result is assigned expr2
• Works almost like C++’s (test ? expr1 : expr2)
• Otherwise, returns value of first false sub-expression
 X or Y or Z  But if the value of expr1 is ever False, the trick
• If all are false, returns value of Z
doesn’t work
• Otherwise, returns value of first true sub-expression  Don’t use it; made unnecessary by conditional
expressions in Python 2.5 (see next slide)
 And and or use lazy evaluation, so no further
expressions are evaluated

Conditional Expressions in Python 2.5

 x = true_value if condition else


false_value
 Uses lazy evaluation:
• First, condition is evaluated Control of Flow
• If True, true_value is evaluated and
returned
• If False, false_value is evaluated and
returned
 Standard use:
x = (true_value if condition else
false_value)

7
if Statements while Loops
if x == 3: >>> x = 3
print “X equals 3.” >>> while x < 5:
elif x == 2:
print x, "still in the loop"
print “X equals 2.”
else:
x = x + 1
print “X equals something else.” 3 still in the loop
print “This is outside the ‘if’.” 4 still in the loop
>>> x = 6
Be careful! The keyword if is also used in the
>>> while x < 5:
syntax of filtered list comprehensions. Note:
print x, "still in the loop"
 Use of indentation for blocks
 Colon (:) after boolean expression
>>>

break and continue assert


 You can use the keyword break inside a  An assert statement will check to make
loop to leave the while loop entirely. sure that something is true during the
course of a program.
 You can use the keyword continue • If the condition if false, the program stops
inside a loop to stop processing the —(more accurately: the program
current iteration of the loop and to throws an exception)
immediately go on to the next one.
assert(number_of_players < 5)

8
Python’s higher-order functions
 Python supports higher-order functions that

List operate on lists similar to Scheme’s


>>> def square(x):
return x*x

Comprehensions >>> def even(x):


return 0 == x % 2
>>> map(square, range(10,20))
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
>>> filter(even, range(10,20))
[10, 12, 14, 16, 18]
>>> map(square, filter(even, range(10,20)))
[100, 144, 196, 256, 324]

 But many Python programmers prefer to use


list comprehensions, instead

List Comprehensions List Comprehensions


 A list comprehension is a programming  The syntax of a list comprehension is
language construct for creating a list based on somewhat tricky
existing lists
[x-10 for x in grades if x>0]
• Haskell, Erlang, Scala and Python have them
 Why “comprehension”? The term is borrowed  Syntax suggests that of a for-loop, an in
from math’s set comprehension notation for operation, or an if statement
defining sets in terms of other sets  All three of these keywords (‘for’, ‘in’, and ‘if’)
 A powerful and popular feature in Python are also used in the syntax of forms of list
• Generate a new list by applying a function to every comprehensions
member of an original list
 Python’s notation:
[ expression for name in list ]
[ expression for name in list ]

9
List Comprehensions List Comprehensions
Note: Non-standard
>>> li = [3, 6, 2, 7] colors on next few  If list contains elements of different types, then
>>> [elem*2 for elem in li]
slides clarify the list expression must operate correctly on the
[6, 12, 4, 14]
comprehension syntax. types of all of list members.
 If the elements of list are other containers,
[ expression for name in list ]
then the name can consist of a container of
• Where expression is some calculation or operation
acting upon the variable name.
names that match the type and “shape” of the
list members.
• For each member of the list, the list comprehension
1. sets name equal to that member,
>>> li = [(‘a’, 1), (‘b’, 2), (‘c’, 7)]
2. calculates a new value using expression,
>>> [ n * 3 for (x, n) in li]
• It then collects these new values into a list which is
the return value of the list comprehension. [3, 6, 21]

[ expression for name in list ] [ expression for name in list ]

List Comprehensions Syntactic sugar


 expression can also contain user-defined List comprehensions can be viewed as
functions. syntactic sugar for a typical higher-order
>>> def subtract(a, b):
functions
return a – b [ expression for name in list ]
>>> oplist = [(6, 3), (1, 7), (5, 5)] map( lambda name: expression, list )
>>> [subtract(y, x) for (x, y) in oplist]
[-3, 6, 0]

[ 2*x+1 for x in [10, 20, 30] ]


map( lambda x: 2*x+1, [10, 20, 30] )

[ expression for name in list ]

10
Filtered List Comprehension Filtered List Comprehension
 Filter determines whether expression is
performed on each member of the list. >>> li = [3, 6, 2, 7, 1, 9]
>>> [elem*2 for elem in li if elem > 4]
 For each element of list, checks if it satisfies the [12, 14, 18]
filter condition.
 Only 6, 7, and 9 satisfy the filter condition
 If the filter condition returns False, that element  So, only 12, 14, and 18 are produce.
is omitted from the list before the list
comprehension is evaluated.

[ expression for name in list if filter] [ expression for name in list if filter]

More syntactic sugar Nested List Comprehensions


Including an if clause begins to show the
 Since list comprehensions take a list as input
benefits of the sweetened form and produce a list as output, they are easily
nested
[ expression for name in list if filt ] >>> li = [3, 2, 4, 1]
map( lambda name . expression, filter(filt, list) ) >>> [elem*2 for elem in
[item+1 for item in li] ]
[ 2*x+1 for x in [10, 20, 30] if x > 0 ] [8, 6, 10, 4]

map( lambda x: 2*x+1,  The inner comprehension produces: [4, 3, 5, 2]


filter( lambda x: x > 0 , [10, 20, 30] )  So, the outer one produces: [8, 6, 10, 4]

[ expression for name in list ]

11
Syntactic sugar
[ e1 for n1 in [ e1 for n1 list ] ]
map( lambda n1: e1,
map( lambda n2: e2, list ) )
For Loops
[2*x+1 for x in [y*y for y in [10, 20, 30]]]
map( lambda x: 2*x+1,
map( lambda y: y*y, [10, 20, 30] ))

For Loops / List Comprehensions For Loops 1


 Python’s list comprehensions provide a
natural idiom that usually requires a for-loop in  A for-loop steps through each of the items in a
other programming languages. collection type, or any other type of object
which is “iterable”
• As a result, Python code uses many fewer
for <item> in <collection>:
for-loops
<statements>
• Nevertheless, it’s important to learn about
for-loops.  If <collection> is a list or a tuple, then the loop
steps through each element of the sequence
 If <collection> is a string, then the loop steps
 Take care! The keywords for and in are also through each character of the string
used in the syntax of list comprehensions, but
for someChar in “Hello World”:
this is a totally different construction.
print someChar

12
For Loops 2 For loops & the range() function
for <item> in <collection>:  Since a variable often ranges over some
<statements> sequence of numbers, the range() function
 <item> can be more than a single variable name returns a list of numbers from 0 up to but not
 When the <collection> elements are themselves including the number we pass to it.
sequences, then <item> can match the structure  range(5) returns [0,1,2,3,4]
of the elements.  So we could say:
 This multiple assignment can make it easier to for x in range(5):
access the individual parts of each element print x
for (x,y) in  (There are more complex forms of range() that
[(a,1),(b,2),(c,3),(d,4)]: provide richer functionality…)
print x

For Loops and Dictionaries

>>> ages = { "Sam" : 4, "Mary" : 3, "Bill" : 2 }


>>> ages
{'Bill': 2, 'Mary': 3, 'Sam': 4}
>>> for name in [Link](): Assignment and Containers
print name, ages[name]
Bill 2
Mary 3
Sam 4
>>>

13
Multiple Assignment with Sequences Empty Containers 1
 Assignment creates a name, if it didn’t exist
 We’ve seen multiple assignment before: already.
x = 3 Creates name x of type integer.
>>> x, y = 2, 3
 Assignment is also what creates named
references to containers.
 But you can also do it with sequences. >>> d = {‘a’:3, ‘b’:4}
 The type and “shape” just has to match.  We can also create empty containers:
>>> li = []
>>> (x, y, (w, z)) = (2, 3, (4, 5)) Note: an empty container
>>> tu = () is logically equivalent to
>>> [x, y] = [4, 5] >>> di = {} False. (Just like None.)
 These three are empty, but of different types

Empty Containers 2
Why create a named reference to empty
container?
• To initialize an empty list, e.g., before using
append String Operations
• This would cause an unknown name error if
a named reference to the right data type
wasn’t created first
>>> [Link](3)
Python complains here about the unknown name ‘g’!
>>> g = []
>>> [Link](3)
>>> g
[3]

14
String Operations String Formatting Operator: %
 A number of methods for the string class  The operator % allows strings to be built out of
perform useful formatting operations: many data items a la “fill in the blanks”
• Allows control of how the final output appears
• For example, we could force a number to display with
>>> “hello”.upper() a specific number of digits after the decimal point
‘HELLO’  Very similar to the sprintf command of C.
>>> x = “abc”
 Check the Python documentation for many >>> y = 34
other handy string operations. >>> “%s xyz %d” % (x, y)
‘abc xyz 34’
 The tuple following the % operator used to fill in
 Helpful hint: use <string>.strip() to strip blanks in original string marked with %s or %d.
off final newlines from lines read from files  Check Python documentation for codes

Printing with Python


 You can print a string to the screen using print
 Using the % operator in combination with print,
we can format our output text
>>> print “%s xyz %d” % (“abc”, 34) String Conversions
abc xyz 34
 Print adds a newline to the end of the string. If you
include a list of strings, it will concatenate them with a
space between them
>>> print “abc” >>> print “abc”, “def”
abc abc def

 Useful trick: >>> print “abc”, doesn’t add newline


just a single space

15
Join and Split Split & Join with List Comprehensions
 Join turns a list of strings into one string  Split and join can be used in a list compre-
hension in the following Python idiom:
<separator_string>.join( <some_list> )
>>> " ".join( [[Link]() for s in "this is a test ".split( )] )
>>> “;”.join( [“abc”, “def”, “ghi”] 'This Is A Test‘
)
>>> # For clarification:
“abc;def;ghi”
>>> "this is a test" .split( )
 Split turns one string into a list of strings ['this', 'is', 'a', 'test']
<some_string>.split( <separator_string> ) >>> [[Link]() for s in "this is a test" .split()]
['This', 'Is', 'A', 'Test’]
>>> “abc;def;ghi”.split( “;” )
[“abc”, “def”, “ghi”]
 Note the inversion in the syntax

Convert Anything to a String


 The builtin str() function can convert an
instance of any data type into a string.
 You define how this function behaves for user-
created data types
 You can also redefine the behavior of this
function for many types.

>>> “Hello ” + str(2)


“Hello 2”

16

You might also like