COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Similar documents
COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Advanced Python. Executive Summary, Session 1

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

CIS192: Python Programming

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

CIS192 Python Programming

CIS192 Python Programming

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Final Exam Version A

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Python. Executive Summary

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Here n is a variable name. The value of that variable is 176.

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

COMP519 Web Programming Lecture 7: Cascading Style Sheets: Part 3 Handouts

CIS192 Python Programming

COMP519 Web Programming Lecture 3: HTML (HTLM5 Elements: Part 1) Handouts

Try and Error. Python debugging and beautification

COMP284 Scripting Languages Lecture 6: Perl (Part 5) Handouts

Introduction to Python! Lecture 2

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CIS192 Python Programming

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

MEIN 50010: Python Flow Control

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

Exceptions CS GMU

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CIS192 Python Programming

Python debugging and beautification

ENGR 102 Engineering Lab I - Computation

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS Programming Languages: Python

Modules and scoping rules

LECTURE 4 Python Basics Part 3

COMP519 Web Programming Lecture 6: Cascading Style Sheets: Part 2 Handouts

Lecture 4. Defining Functions

CS 11 python track: lecture 3. n Today: Useful coding idioms

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Introduction to Python programming, II

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Iterators & Generators

databuild Documentation

Exceptions & a Taste of Declarative Programming in SQL

Lecture 17: Classes (Chapter 15)

Parsing Scheme (+ (* 2 3) 1) * 1

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts

Variable and Data Type I

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

Execution order. main()

Lecture 4. Defining Functions

61A Lecture 26. Monday, October 31

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Beyond Blocks: Python Session #1

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Lecture #12: Quick: Exceptions and SQL

COMP 204: Sets, Commenting & Exceptions

CIS192 Python Programming

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

INTERPRETERS AND TAIL CALLS 9

Defining Functions and Using Built-ins

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Data Structures I: Linked Lists

Chapter 1. Fundamentals of Higher Order Programming

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts

Exceptions. raise type(message) raise Exception(message)

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Programming with Python. May 4, 2017

Sequences and iteration in Python

ENGR 101 Engineering Design Workshop

egrapher Language Reference Manual

Programming with Python

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

FILE HANDLING AND EXCEPTIONS

Reminder About Functions

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Abstract Data Types. David E. Culler CS8 Computational Structures in Data Science Lecture 7 March 7, 2016

COMP-520 GoLite Tutorial

Lecture 7: Lambda & Abstract Data Types

Python: common syntax

CS 314 Principles of Programming Languages

Transcription:

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