Lecture 5. Defining Functions

Similar documents
Lecture 4. Defining Functions

Lecture 4. Defining Functions

Lecture 4. Defining Functions

Lecture 7. Memory in Python

Lecture 10. Memory in Python

PREPARING FOR PRELIM 1

Readings for This Lecture

Announcements for this Lecture

Lecture 4: Defining Functions

Lecture 9. Memory and Call Stacks

Announcements For This Lecture

Announcements for the Class

Lecture 4: Defining Functions (Ch ) CS 1110 Introduction to Computing Using Python

Lecture 12. Lists (& Sequences)

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules

Assignment 2: Due Friday Feb 13 at 6pm

CS 1110 Prelim 1 October 4th, 2012

Conditionals & Control Flow

CS 1110: Introduction to Computing Using Python Lists and Sequences

CMSC 201 Fall 2018 Lab 04 While Loops

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

PREPARING FOR THE FINAL EXAM

CS1 Lecture 3 Jan. 22, 2018

Lecture 8. Conditionals & Control Flow

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

PREPARING FOR PRELIM 2

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Computer Science II Lecture 1 Introduction and Background

Semester 2, 2018: Lab 1

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

CS Prelim 1 Review Fall 2016

CIT 590 Homework 5 HTML Resumes

CMSC201 Computer Science I for Majors

CSE : Python Programming

CS1 Lecture 3 Jan. 18, 2019

61A Lecture 7. Monday, September 15

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Lecture 6: Specifications & Testing

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

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

Introduction to Programming System Design CSCI 455x (4 Units)

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

You must pass the final exam to pass the course.

61A Lecture 7. Monday, September 16

CS Prelim 1 Review Fall 2017

Announcements For This Lecture

CS Prelim 1 Review Fall 2013

CMSC 201 Computer Science I for Majors

Lab 4 Fruitful Functions

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

1.00/1.001 Tutorial 1

CMSC 201 Spring 2017 Lab 01 Hello World

CS1 Lecture 13 Feb. 13, 2019

CS1110 Lab 1 (Jan 27-28, 2015)

Lecture 1. Course Overview Types & Expressions

CS1110. Lecture 6: Function calls

Part III Appendices 165

Using IDLE for

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

CS 1110 Prelim 1 October 17th, 2013

Lecture 9: Memory in Python

Downloaded from Chapter 2. Functions

CS 1110, Spring 2018: Prelim 1 study guide Prepared Tuesday March 6, 2018

1.00 Tutorial 1. Introduction to 1.00

Lecture 1. Course Overview, Python Basics

CMPSC 111 Introduction to Computer Science I Fall 2016 Lab 8 Assigned: October 26, 2016 Due: November 2, 2016 by 2:30pm

Lecture 13. For-Loops

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

CMSC 201 Spring 2018 Lab 01 Hello World

Chapter 2 Writing Simple Programs

Lecture 1. Course Overview, Python Basics

CS Prelim 1 Review Fall 2018

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

CS Prelim 1 Review Fall 2013

CS 051 Homework Laboratory #2

Lecture 2. Variables & Assignment

CSCI544, Fall 2016: Assignment 1

61A Lecture 3. Friday, September 5

CS 1110 Regular Prelim 1, March 14th, 2017

CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points

Pattern Maker Lab. 1 Preliminaries. 1.1 Writing a Python program

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Tips from the experts: How to waste a lot of time on this assignment

Lecture 10: Lists and Sequences

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Lab 1: Setup 12:00 PM, Sep 10, 2017

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

PREPARING FOR THE FINAL EXAM

61A LECTURE 1 FUNCTIONS, VALUES. Steven Tang and Eric Tzeng June 24, 2013

Lecture 19. Operators and Abstraction

Lecture 22. While Loops

Announcements for This Lecture

Read and fill in this page now. Your lab section day and time: Name of the person sitting to your left: Name of the person sitting to your right:

CS1110. Lecture 6: Function calls

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

Transcription:

Lecture 5 Defining Functions

Announcements for this Lecture Last Call Quiz: About the Course Take it by tomorrow Also remember the survey Readings Sections 3.5 3.3 today Also 6.-6.4 See online readings for Tues Install Party: 7pm Sunday ACCEL Lab 8/30/2 Modules & Functions 2

First Assignment Posted This Weekend Due Monday, September 7 Submit earlier so we can start iterative feedback process Work alone or with one partner Partners group themselves on the CMS Only one person submits the files. Partners must do the work together, sit next to each other, with each taking turns driving (writing the code) Academic Integrity Never look at someone s code or show yours to someone else Never possess someone else s code (except your partner) 2/2/2 Classes 3

One-on-One Sessions Starting Tomorrow: /2-hour one-on-one sessions Bring computer and work with instructor, TA or consultant Hands, dedicated help with Lab 2 and/or Lab 3 To prepare for assignment, but no help assignment itself Limited availability: we cannot get to everyone Students with experience or confidence should hold back Sign up online in CMS: first come, first served Choose assignment One-on-One Pick a time that works for you; will add slots as possible Can sign up starting at pm TODAY 2/2/2 Classes 4

Special Module for Assignment: urllib2 urllib2 has a function called urlopen(url) Single argument: string with a url Example: urllib2.urlopen('http://www.cornell.edu') Returns an object: a webpage! (But type() will identify it as an instance) If url is invalid, Python will crash Object has no attributes, but two methods: geturl(): Returns the url of the website read(): Returns webpage HTML as a string 2/2/2 Classes 5

We Write Programs to Do Things Functions are the key doers Function Call Command to do the function greet('walker') argument to assign to n Function Header Function Definition Defines what function does def greet(n): declaration of parameter n print 'Hello '+n+'!' Parameter: variable that is listed within the parentheses of a method header. Argument: a value to assign to the method parameter when it is called Function Body (indented) 9/7/2 Classes 6

Anatomy of a Function Definition name def greet(n): """Prints a greeting to the name n parameters Precondition: n is a string " representing a person s name""" print 'Hello '+n+'!' print 'How are you?' Function Header Docstring Specification Statements to execute when called The vertical line indicates indentation Use vertical lines when you write Python on exams so we can see indentation 2/2/2 Classes 7

Procedures vs. Fruitful Functions Procedures Functions that do something Call them as a statement Example: greet('walker') Fruitful Functions Functions that give a value Call them in an expression Example: x = round(2.56,) Historical Aside Historically function = fruitful function But now we use function to refer to both 2/2/2 Classes 8

The return Statement Fruitful functions require a return statement Format: return <expression> Provides value when call is used in an expression Also stops executing the function! Any statements after a return are ignored Example: temperature converter function def to_centigrade(x): """Returns: x converted to centigrade""" return 5*(x-32)/9.0 2/2/2 Classes 9

Functions and Modules The purpose of modules is function definitions Function definitions are written in module file Import the module to call the functions Your Python workflow (right now) is. Write a function in a module (a.py file) 2. Open up the command shell 3. Move to the directory with this file 4. Start Python (type python) 5. Import the module 6. Try out the function 2/2/2 Classes 0

Aside: Constants Modules often have variables outside a function We call these global variables Accessible once you import the module Global variables should be constants Variables that never, ever change Mnemonic representation of important value Example: math.pi, math.e in math In this class, constant names are capitalized! So we can tell them apart from non-constants 2/2/2 Classes

Module Example: Temperature Converter # temperature.py """Conversion functions between fahrenheit and centrigrade""" # Functions def to_centigrade(x): """Returns: x converted to centigrade""" return 5*(x-32)/9.0 def to_fahrenheit(x): """Returns: x converted to fahrenheit""" return 9*x/5.0+32 # Constants FREEZING_C = 0.0 # temp. water freezes Style Guideline: Two blank lines between function definitions 2/2/2 Classes 2

How Do Functions Work? Draw template on a piece of paper Function Frame: Representation of function call A conceptual model of Python Draw parameters as variables (named boxes) Number of statement in the function body to execute next Starts with function name instruction counter parameters local variables (later in lecture) 9/0/2 Methods & Constructors 3

Example: to_centigrade(50.0). Draw a frame for the call 2. Assign the argument value to the parameter (in frame) 3. Execute the function body Look for variables in the frame If not there, look for global variables with that name 4. Erase the frame for the call Initial call frame (before exec body) to_centigrade x 50.0 def to_centigrade(x): return 5*(x-32)/9.0 next line to execute 9/0/2 Methods & Constructors 4

Example: to_centigrade(50.0). Draw a frame for the call 2. Assign the argument value to the parameter (in frame) 3. Execute the function body Look for variables in the frame If not there, look for global variables with that name 4. Erase the frame for the call to_centigrade x Executing the return statement 50.0 def to_centigrade(x): return 5*(x-32)/9.0 The return terminates; no next line to execute 9/0/2 Methods & Constructors 5

Example: to_centigrade(50.0). Draw a frame for the call 2. Assign the argument value to the parameter (in frame) 3. Execute the function body Look for variables in the frame If not there, look for global variables with that name 4. Erase the frame for the call def to_centigrade(x): return 5*(x-32)/9.0 But don t actually erase on an exam 9/0/2 Methods & Constructors 6

Call Frames vs. Global Variables This does not work: def swap(a,b): 2 """Swap vars a & b""" tmp = a a = b 3 b = tmp swap >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame a b 2 2/2/2 Classes 7

Call Frames vs. Global Variables This does not work: def swap(a,b): 2 3 """Swap vars a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame swap 2 a b 2 tmp 2/2/2 Classes 8

Call Frames vs. Global Variables This does not work: def swap(a,b): 2 3 """Swap vars a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame swap 3 a 2 b 2 tmp 2/2/2 Classes 9

Call Frames vs. Global Variables This does not work: def swap(a,b): 2 3 """Swap vars a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame swap 2 a b 2 tmp 2/2/2 Classes 20

Example with Objects Mutable objects can be altered in a function call Object vars hold names! Folder accessed by both global var & parameter Example: def incr_x(q): q.x = q.x + >>> p = Point() >>> incr_x(p) Global STUFF 430022 p 430022 x 0.0 Call Frame Point incr_x q 430022 2/2/2 Classes 2

Example with Objects Mutable objects can be altered in a function call Object vars hold names! Folder accessed by both global var & parameter Example: def incr_x(q): q.x = q.x + >>> p = Point() >>> incr_x(p) Global STUFF 430022 p x 0.0.0 Call Frame incr_x q 430022 430022 Point 2/2/2 Classes 22