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

Size: px
Start display at page:

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

Transcription

1 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

2 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

3 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

4 Control Structures For-loops for i in range (3): print (i) For-loops for i in range (0,7,3): print (i) // JavaScript for (i = 3, j = 3; j >= 0; i++, j - -) document. writeln (i + " - " + j + " - " + i*j) # Python for i, j in zip ( range (3,100), range (3, -1, -1)): print ( str (i) + " - " + str (j) + " - " + str (i*j)) COMP519 Web Programming Lecture 20 Slide L20 3

5 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

6 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 = / -1 = / 1 = / 2 = 5 COMP519 Web Programming Lecture 20 Slide L20 5

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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, Harold Cohen Library S29 or E-book COMP519 Web Programming Lecture 20 Slide L20 18

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

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions

More information

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

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Control

More information

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

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Functions and Functional Programming Harry Smith University of Pennsylvania January 25, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 3 January 25, 2018 1 / 39

More information

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

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Robert Rand University of Pennsylvania February 03, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 03, 2016 1 / 23 Outline 1 Function Arguments

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Eric Kutschera University of Pennsylvania January 30, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 January 30, 2015 1 / 31 Questions Homework

More information

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

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

Final Exam Version A

Final Exam Version A CS112 Spring 2014 Dr. Kinga Dobolyi Final Exam Version A Do not open this exam until you are told. Read these instructions: 1. This is a closed book exam. No calculators, notes, or other aids are allowed.

More information

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS (download slides and.py files and follow along!) 6.0001 LECTURE 7 6.0001 LECTURE 7 1 WE AIM FOR HIGH QUALITY AN ANALOGY WITH SOUP You are making soup but bugs

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

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

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

COMP519 Web Programming Lecture 7: Cascading Style Sheets: Part 3 Handouts COMP519 Web Programming Lecture 7: Cascading Style Sheets: Part 3 Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

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

COMP519 Web Programming Lecture 3: HTML (HTLM5 Elements: Part 1) Handouts COMP519 Web Programming Lecture 3: HTML (HTLM5 Elements: Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

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

COMP284 Scripting Languages Lecture 6: Perl (Part 5) Handouts COMP284 Scripting Languages Lecture 6: Perl (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

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

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt. Lecture 4 while and for loops if else test Tuples Functions Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.edu Launching Python > python Quick Reminder: while Loop Example >>>

More information

Exceptions CS GMU

Exceptions CS GMU Exceptions CS 112 @ GMU Exceptions When an unrecoverable action takes place, normal control flow is abandoned: an exception value crashes outwards until caught. various types of exception values can be

More information

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

Python debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

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

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3] What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

More information

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

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

COMP519 Web Programming Lecture 6: Cascading Style Sheets: Part 2 Handouts COMP519 Web Programming Lecture 6: Cascading Style Sheets: Part 2 Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Remember: quiz about the course AI policy Have posted grades for completed quizes Right now, missing ~130 enrolled students If did not receive at least

More information

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

CS 11 python track: lecture 3. n Today: Useful coding idioms CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise

More information

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

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

More information

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

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

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

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013 CS61A Lecture 32 Amir Kamil UC Berkeley April 5, 2013 Announcements Hog revisions due Monday HW10 due Wednesday Make sure to fill out survey on Piazza We need to schedule alternate final exam times for

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

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

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 PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

databuild Documentation

databuild Documentation databuild Documentation Release 0.0.10 Flavio Curella May 15, 2015 Contents 1 Contents 3 1.1 Installation................................................ 3 1.2 Quickstart................................................

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Lecture 17: Classes (Chapter 15)

Lecture 17: Classes (Chapter 15) http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 17: Classes (Chapter 15) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

More information

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

Parsing Scheme (+ (* 2 3) 1) * 1 Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes

More information

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

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

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

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.) CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

More information

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

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know? Python Compact February 7, 2018 1 Python Compact 1.0.1 Claus Führer, Lund University Short introduction to Python for participants of the course ** Numerical Methods - Review and Training ** Volvo Cars,

More information

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.

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. CSE 3302 Test 1 1. Preprocessor macros are associated with: A. C B. Java C. JavaScript D. Pascal 2. (define x (lambda (y z) (+ y z))) is an example of: A. Applying an anonymous function B. Defining a function

More information

Execution order. main()

Execution order. main() Functions Execution order When you load and run a Python module (file), the statements and definitions in the file are executed in the order in which they occur Executing a def defines a function, it doesn

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Remember: quiz about the course AI policy Have posted grades for completed quizes Right now, missing ~90 enrolled students If did not receive perfect,

More information

61A Lecture 26. Monday, October 31

61A Lecture 26. Monday, October 31 61A Lecture 26 Monday, October 31 Programming Languages Computers have software written in many different languages Machine languages: statements can be interpreted by hardware All data are represented

More information

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

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

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

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99 1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

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

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

INTERPRETERS AND TAIL CALLS 9

INTERPRETERS AND TAIL CALLS 9 INTERPRETERS AND TAIL CALLS 9 COMPUTER SCIENCE 61A April 9, 2015 We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In order

More information

Defining Functions and Using Built-ins

Defining Functions and Using Built-ins Defining Functions and Using Built-ins Functions are the fundamental unit of work in Python. A function in Python performs a task and returns a result. In this chapter, we will start with the basics of

More information

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

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

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

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

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

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like? Chapter 3 - Simple JavaScript - Programming Basics Lesson 1 - JavaScript: What is it and what does it look like? PP presentation JavaScript.ppt. Lab 3.1. Lesson 2 - JavaScript Comments, document.write(),

More information

Data Structures I: Linked Lists

Data Structures I: Linked Lists Lab 4 Data Structures I: Linked Lists Lab Objective: Analyzing and manipulating data are essential skills in scientific computing. Storing, retrieving, and rearranging data take time. As a dataset grows,

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

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

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

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

Exceptions. raise type(message) raise Exception(message) Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ TUPLES 2 Tuples as Immutable Sequences tuple =

More information

Programming with Python. May 4, 2017

Programming with Python. May 4, 2017 Programming with Python May 4, 2017 Python and IPython Python is an interpreter. It translates source code into instructions that the processor can understand. Different ways of running python: python

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

More information

Reminder About Functions

Reminder About Functions Reminder About Functions (let ((z 17)) (let ((z 3) (a ) (x (lambda (x y) (- x (+ y z))))) (let ((z 0) (a )) (x z a)))) int h, i; void B(int w) { int j, k; i = 2*w; w = w+1; void A(int x, int y) { bool

More information

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

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.) CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

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

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics CS2304: Advanced Function Topics Functions With An Arbitrary Number of Parameters Let s say you wanted to create a function where you don t know the exact number of parameters. Python gives you a few ways

More information

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

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python Outline Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer Universität des Saarlandes October 6th, 2009 Outline Outline Today s Topics: 1 More Examples 2 Cool Stuff 3 Text Processing

More information

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

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

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

Abstract Data Types. David E. Culler CS8 Computational Structures in Data Science   Lecture 7 March 7, 2016 Abstract Data Types David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 7 March 7, 2016 Computational Concepts Toolbox Data type: values, literals,

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

Lecture 7: Lambda & Abstract Data Types

Lecture 7: Lambda & Abstract Data Types UC Berkeley EECS Adj. Ass. Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture 7: Lambda & Abstract Data Types Computational Concepts Toolbox Data type: values, literals, operations,

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

More information