COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool
Contents 1 Control Structures For-loops Try Statements 2 Functions Defining a Function Calling a Function Variable-length Argument Lists Static Variables Nested Function Definitions 3 Further Reading COMP519 Web Programming Lecture 20 Slide L20 1
Control Structures For-loops For-loops for-loops in Python take the form for var1,..., varn in sequence : else : var1,..., varn are variables sequence is a sequence (list, range, tuple) The loop iterates over the elements of sequence In each iteration an element E of sequence is assigned to var1,..., varn: var1,..., varn = E if there is more than one variable, then E must itself be a sequence with a matching number of elements The optional else-clause is executed after the last iteration of the loop unless the loop is left via a break, exception, or error COMP519 Web Programming Lecture 20 Slide L20 2
Control Structures For-loops for i in range (3): print (i) 0 1 2 For-loops for i in range (0,7,3): print (i) 0 3 6 // JavaScript for (i = 3, j = 3; j >= 0; i++, j - -) document. writeln (i + " - " + j + " - " + i*j) 3-3 - 9 4-2 - 8 5-1 - 5 6-0 - 0 # Python for i, j in zip ( range (3,100), range (3, -1, -1)): print ( str (i) + " - " + str (j) + " - " + str (i*j)) 3-3 - 9 4-2 - 8 5-1 - 5 6-0 - 0 COMP519 Web Programming Lecture 20 Slide L20 3
Control Structures For-loops For-loops Example: Iteration over a list oldnames = [" Dave Jackson ", " Ullrich Hustadt "] newnames = [] for name in oldnames : nameparts = name. split (" ") newnames. append ( nameparts [1] + ", "+ nameparts [0]) print ( newnames ) [ Jackson, Dave, Hustadt, Ullrich ] Example: Iteration over a string for letter in Jim : print ( letter, letter. upper ()) J J i I m M COMP519 Web Programming Lecture 20 Slide L20 4
Control Structures Break and Continue For-loops The break command be used in while- and for-loops and discontinues the execution of the loop while value < 100: if value == 0: break ; value += 1 The continue command stops the execution of the current iteration of a loop and moves the execution to the next iteration for x in range ( -2,+2,1): if x == 0: continue print ("10 / " + str ( x) + " = " + str (10/ x)) 10 / -2 = -5 10 / -1 = -10 10 / 1 = 10 10 / 2 = 5 COMP519 Web Programming Lecture 20 Slide L20 5
Control Structures Try Statements Try Statements Python offers try statements to deal with exceptions (errors other than SyntaxErrors) try : except exception : except exception :... except : finally : First, the try-clause is executed If no exception occurs, all except-clauses are skipped If an exception occurs, execution of the try-clause stops and a matching except-clause (if it exists) is executed An except-clause without exception matches any exception The optional finally-clause is always executed COMP519 Web Programming Lecture 20 Slide L20 6
Control Structures Try Statements Try Statements import math try : z = x / y except NameError : # Either x or y was not inialised z = None except ZeroDivisionError : # A division by zero has occurred, i. e. y == 0 if x!= 0: z = math. copysign (1,x)* math. inf else : z = math. nan except : # Another error has occured, e. g. a TypeError z = None print (z) Initial value x = 1 x = 0 x = 1 x = 1 of x and y y = 0 y = 0 y = 1 y = 1 y = 1 Output inf nan None None 1 COMP519 Web Programming Lecture 20 Slide L20 7
Control Structures Else Clause Revisited Try Statements The example below illustrates the usefulness of else-clauses in loop constructs: for x in data : if acceptable ( x): break else : raise ValueError (" No acceptable value found ") # Computation with x continues here COMP519 Web Programming Lecture 20 Slide L20 8
Functions Defining a Function Defining a Function Functions are elements of type function and can be defined as follows: def identifier ( param1, param2,...): docstring The function name identifier is case-sensitive The function name must be followed by parentheses A function has zero, one, or more parameters that are variables Parameters are not typed Parameters can be given default values param1 = value Parameter of the form *param1 and **param1 can take a variable number of arguments docstring is a string describing the function and will be returned by help(identifier) or identifier. doc is a non-empty sequence of statements COMP519 Web Programming Lecture 20 Slide L20 9
Functions Defining a Function Defining a Function Functions are elements of type function and can be defined as follows: def identifier ( param1, param2,...): The return statement return value can be used to terminate the execution of a function and to make the optional value the return value of the function The return value does not have to be of a primitive type A function can contain more than one return statement Different return statements can return values of different types there is no return type for a function If the executation of a function ends without encountering a return statement or ends with a return statement without value then the function returns the value None COMP519 Web Programming Lecture 20 Slide L20 10
Functions Calling a Function Calling a Function A function is called by using the function name followed by a list of arguments in parentheses def identifier ( param1, param2,...):... identifier (arg1, arg2,...)... # Function call Arguments are passed by assignment param1 = arg1, param2 = arg2... The number of arguments has to match the number of parameters (excluding * and ** parameters) too many or too few arguments result in TypeError def exp (base, exp ): return base ** exp exp (2,3) # returns 8 exp (2,3,1) # TypeError exp (2) # TypeError COMP519 Web Programming Lecture 20 Slide L20 11
Functions Calling a Function Calling a Function A function is called by using the function name followed by a list of arguments in parentheses def identifier ( param1, param2,...):... identifier (arg1, arg2,...)... # Function call Arguments can be specified as keyword arguments param=value, where param matches one of the parameters in the function definition having good parameter names pays off The order of keyword arguments is irrelevant makes modifications easier def exp (base, exp ): return base ** exp exp (2,3) # returns 8 exp ( base =2, exp =3) # returns 8 exp ( exp =3, base =2) # returns 8 COMP519 Web Programming Lecture 20 Slide L20 12
Functions Variable-length Argument Lists Variable-length Argument Lists def identifier ( param1, param2,...): For a parameter *param1, param1 is initialised to a tuple receiving any excess positional parameters, defaulting to the empty tuple def sumall (* args ): # no minimum number of arguments sum = 0 for val in args : sum = sum + val return sum sumall () # returns 0 sumall (5) # returns 5 sumall (5,4,3) # returns 12 COMP519 Web Programming Lecture 20 Slide L20 13
Functions Variable-length Argument Lists Variable-length Argument Lists def identifier ( param1, param2,...): For a parameter **param2, param2 is initialised to a dictionary mapping any excess keyword arguments, defaulting to an empty dictionary def printfile ( file,** kwargs ): # at least one arguments if duplex in kwargs and kwargs [ duplex ]: print ( Duplex option enabled ) if orientation in kwargs and \ kwargs [ orientation ] == landscape : print ( Landscape option enabled ) if orientation in kwargs and \ kwargs [ orientation ] == portrait : print ( Portrait option enabled ) print ( Printing, file ) printfile( python1.py ) No option enabled printfile( python1.py,orientation= landscape ) Landscape option enabled printfile( python1.py,duplex= True ) Duplex option enabled printfile( python1.py,orientation= landscape, Both Landscape and duplex= True ) Duplex option enabled COMP519 Web Programming Lecture 20 Slide L20 14
Functions Variable-length Argument Lists Variable-length Argument Lists When mixing ordinary parameters / arguments, keyword arguments and variable-length argument lists, parameters and arguments need to occur in a particular order to work correctly In a function definition we have 1 Normal parameters 2 *param1 3 **param2 def applyfunc ( func, resultformat,* arg,* kwargs ): In a function call we have 1 Normal (positional) arguments 2 Keyword arguments applyfunc ( lambda x: 2*x, list,1,2,3, debug = True ) COMP519 Web Programming Lecture 20 Slide L20 15
Functions Static Variables JavaScript Functions and Static Variables Python does not have a static keyword to declare a variable to be static and preserve its value between different calls of a function A solution is to use a function attribute instead def counter (): try : counter. count += 1 except AttributeError : counter. count = 1 return counter. count print ("1: static count = ", counter ()) print ("2: static count = ", counter ()) print ("3: global counter. count = ", counter. count ) 1: static count = 1 2: static count = 2 3: global counter. count = 2 As the example shows the function property is public COMP519 Web Programming Lecture 20 Slide L20 16
Functions Nested Function Definitions Nested Function Definitions Function definitions can be nested in Python By default, inner functions can not be invoked from outside the function they are defined in def bubble_sort ( arr ): def swap (i, j): tmp = arr [i] arr [i] = arr [j] arr [j] = tmp if not ( isinstance (arr, list )): raise TypeError (" bubble_sort argument must be a list ") for i in range (0, len ( arr ) -1): for j in range (0, len ( arr )-i -1): if arr [j +1] < arr [j]: swap (j, j +1) return arr COMP519 Web Programming Lecture 20 Slide L20 17
Further Reading Revision and Further Reading Read Chapter 26: The Python Language: User-Defined Functions Chapter 26: The Python Language: Python Errors and Exception Handling of S. Schafer: Web Standards Programmer s Reference. Wiley Publishing, 2005. Harold Cohen Library 518.532.S29 or E-book http://library.liv.ac.uk/record=b2174141 COMP519 Web Programming Lecture 20 Slide L20 18