Lecture 4: Defining Functions

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

Lecture 4. Defining Functions

Lecture 4. Defining Functions

Lecture 7. Memory in Python

Lecture 3: Functions & Modules

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 5. Defining Functions

Conditionals & Control Flow

Lecture 2: Variables & Assignments

Lecture 5: Strings

CS1110. Lecture 6: Function calls

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS1110. Lecture 6: Function calls

Lecture 3. Functions & Modules

Lecture 10. Memory in Python

Lecture 3. Functions & Modules

Lecture 9. Memory and Call Stacks

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

Lecture 4. Defining Functions

Lecture 6: Specifications & Testing

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

Lecture 9: Memory in Python

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 11: Iteration and For-Loops

Lecture 17: Classes (Chapter 15)

Iteration and For Loops

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

CS 1110, LAB 13: SEQUENCE ALGORITHMS

PREPARING FOR PRELIM 1

Lecture 17: Classes (Chapter 15)

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

CS 1110, LAB 3: STRINGS; TESTING

61A Lecture 7. Monday, September 15

Lecture 24: Loop Invariants

Lecture 19: Subclasses & Inheritance (Chapter 18)

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

CS 1110: Introduction to Computing Using Python Lists and Sequences

CS 1110: Introduction to Computing Using Python Loop Invariants

Lecture 18: Using Classes Effectively (Chapter 16)

Lecture 3. Strings, Functions, & Modules

Lecture 10: Lists and Sequences

Lecture 20: While Loops (Sections 7.3, 7.4)

CS1 Lecture 4 Jan. 23, 2019

61A Lecture 7. Monday, September 16

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

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

CS1 Lecture 3 Jan. 18, 2019

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

61A Lecture 2. Wednesday, September 4, 2013

isinstance and While Loops

CS1 Lecture 4 Jan. 24, 2018

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

Lecture 1. Course Overview Types & Expressions

CS 1110, LAB 03: STRINGS; TESTING First Name: Last Name: NetID:

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS1 Lecture 15 Feb. 18, 2019

CS Lecture 25: Models, Views, Controllers, and Games. Announcements

4. Modules and Functions

CS Lecture 26: Subclasses in Event-driven Programs A7 is out! Get started right away you need time to ask questions.

Unit 10: Data Structures CS 101, Fall 2018

CS1 Lecture 3 Jan. 22, 2018

PREPARING FOR THE FINAL EXAM

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

COMP1730/COMP6730 Programming for Scientists. Functions

CS 1110 Prelim 1 October 17th, 2013

CIS192: Python Programming

UNIT 2B An Introduction to Programming. Announcements

PREPARING FOR THE FINAL EXAM

Lecture 1. Course Overview, Python Basics

Use the Associative Property of Multiplication to find the product.

61A Lecture 6. Monday, February 2

Lecture 13. For-Loops

CS1 Lecture 13 Feb. 13, 2019

61A Lecture 2. Friday, August 28, 2015

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

CS1 Lecture 15 Feb. 19, 2018

Lecture 8. Conditionals & Control Flow

CS 102 Lab 3 Fall 2012

CS 115 Exam 2 (Section 1) Fall 2017 Thu. 11/09/2017

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

CS 051 Homework Laboratory #2

CS 1110 SPRING 2016: LAB 3: PRACTICE FOR A2 (Feb 23-24)

CS 1110 Prelim 1 October 4th, 2012

Lecture 1. Course Overview, Python Basics

CME 193: Introduction to Scientific Python Lecture 1: Introduction

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

Name Section: M/W T/TH Number Definition Matching (8 Points)

S206E Lecture 19, 5/24/2016, Python an overview

CS64 Week 5 Lecture 1. Kyle Dewey

61A Lecture 9. Friday, September 20

Announcements. Last modified: Fri Sep 8 00:59: CS61B: Lecture #7 1

CS2102, B15 Exam 2. Name:

Semester 2, 2018: Lab 1

Module 01: Introduction to Programming in Python

CSCI-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CS1 Lecture 5 Jan. 25, 2019

Sorting and Searching

Problem 1 (a): List Operations

CS 1110 Prelim 1 October 12th, 2017

Lecture 1: Introduction, Types & Expressions

Transcription:

http://www.cs.cornell.edu/courses/cs0/208sp Lecture 4: Defining Functions (Ch. 3.4-3.) CS 0 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

Things to Do Before Next Class Readings: Sections 8., 8.2, 8.4, 8.5, first paragraph of 8.9 Labs: Go to Lab! (Lab 2 is this week) Get Credit for Lab : can be checked off during Tuesday's consulting hours 4:30-9:30 in the ACCEL lab cannot be checked off after 3:45pm Wednesday check online if you received credit: http://www.cs.cornell.edu/courses/cs0/ 208sp/labs/index.php 2

Check out Piazza Post @2 https://piazza.com/class/jckqwmqflaz6i?cid=2 3

4

5

From last time: Function Calls Function expressions have the form fun(x,y, ) Examples (math functions that work in Python): round(2.34) max(a+3,24) function name argument 7

From last time: Modules Modules provide extra functions, variables Access them with the import command Example: module math >>> import math >>> math.cos(2.0) -0.4646836547424 >>> math.pi 3.4592653589793 8

From last time: Modules Module Text # my_module.py """This is a simple module. It shows how modules work""" Interactive Python >>> import my_module >>> my_module.x 9 x = +2 x = 3*x We discussed how to make module variables Have not covered how to make functions 9

simple_math.py >>> import simple_math >>> simple_math.increment() 2 >>> simple_math. increment(2) 3 0

Anatomy of a Function Definition name parameters def increment(n): Function Header """Returns: the value of n+""" return n+ Docstring Specification Statements to execute when called also called Function Body The vertical line indicates indentation Use vertical lines when you write Python on exams so we can see indentation

The return Statement Passes a value from the function to the caller Format: return <expression> Any statements after return are ignored Optional (if absent, special value None will be sent back) 2

Function Calls vs. Definitions Function Call Command to do the function Function Definition Defines what function does >>> simple_math.increment(23) 24 >>> argument to assign to n def increment(n): return n+ declaration of parameter n Parameter: variable that is listed within the parentheses of a function header. Argument: a value to assign to the function parameter when it is called 3

Using simple_math.py Module Text Interactive Python # simple_math.py Python skips >>> import simple_math """module with two simple math functions""" Python skips def increment(n): """Returns: n+""" return n+ Python learns the function definition Python skips everything inside the function Repeat for all functions in module 4

Using simple_math.py Module Text # simple_math.py """module with two simple math functions""" def increment(n): """Returns: n+""" return n+ Interactive Python >>> import simple_math >>> simple_math.increment(23) Now Python executes the function body Python knows what this is! 5

Using simple_math.py Module Text # simple_math.py """module with two simple math functions""" Interactive Python >>> import simple_math >>> simple_math.increment(23) def increment(n): """Returns: n+""" return n+ 6

Using simple_math.py Module Text # simple_math.py """module with two simple math functions""" Interactive Python >>> import simple_math >>> simple_math.increment(23) 24 def increment(n): """Returns: n+""" return n+ 7

Understanding How Functions Work We will draw pictures to show what is in memory Function Frame: Representation of function call 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) Note: slightly different than in the book (3.9) Please do it this way. 8

Example: get_feet >>> import height >>> height.get_feet(68) def get_feet(height_in_inches): return height_in_inches // INCHES_PER_FOOT 9

Example: get_feet(68) PHASE : Set up call frame next line to execute. Draw a frame for the call 2. Assign the argument value to the parameter (in frame) 3. Indicate next line to execute get_feet height_in_inches 68 def get_feet(height_in_inches): return height_in_inches // INCHES_PER_FOOT 20

Example: get_feet(68) PHASE 2: Execute function body Return statement creates a special variable for result get_feet height_in_inches 68 RETURN 5 def get_feet(height_in_inches): return height_in_inches // INCHES_PER_FOOT 2

Example: get_feet(68) PHASE 2: Execute function body The return terminates; no next line to execute get_feet height_in_inches 68 RETURN 5 def get_feet(height_in_inches): return height_in_inches // INCHES_PER_FOOT 22

Example: get_feet(68) PHASE 3: Erase call frame get_feet height_in_inches 68 RETURN 5 def get_feet(height_in_inches): return height_in_inches // INCHES_PER_FOOT 23

Example: get_feet(68) PHASE 3: Erase call frame But don t actually erase on an exam ERASE WHOLE FRAME def get_feet(height_in_inches): return height_in_inches // INCHES_PER_FOOT 24

Local Variables () Call frames can make local variables >>> import room_numbers >>> room_numbers.lab_rooms() lab_rooms def lab_rooms(): 2 red_room = 235 orange_room = 236 25

Local Variables (2) Call frames can make local variables >>> import room_numbers >>> room_numbers.lab_rooms() lab_rooms 2 def lab_rooms(): red_room 235 2 red_room = 235 orange_room = 236 26

Local Variables (3) Call frames can make local variables >>> import room_numbers >>> room_numbers.lab_rooms() lab_rooms def lab_rooms(): red_room 235 2 red_room = 235 orange_room = 236 orange_room 236 RETURN NONE 27

Local Variables (4) Call frames can make local variables >>> import room_numbers >>> room_numbers.lab_rooms() 2 def lab_rooms(): red_room = 235 orange_room = 236 ERASE WHOLE FRAME Variables are gone! This function is useless. 28

Exercise Time 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> foo(3,4) Function Call What does the frame look like at the start? 29

Which One is Closest to Your Answer? A: B: foo a 3 b 4 foo a 3 b 4 x a C: D: foo a 3 b 4 foo a 3 b 4 x 3 x y 30

Exercise Time 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> foo(3,4) B: Function Call foo a 3 b 4 What is the next step? 3

Which One is Closest to Your Answer? A: B: foo 2 a 3 b 4 foo a 3 b 4 x 3 C: D: foo 2 a 3 b 4 x 3 foo 2 a 3 b 4 x 3 y 32

Exercise Time 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> foo(3,4) C: Function Call foo 2 a 3 b 4 x 3 What is the next step? 33

Exercise Time 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> foo(3,4) Function Call foo 3 a 3 b 4 x 3 y 4 What is the next step? 34

Which One is Closest to Your Answer? A: B: foo 3 foo RETURN 6 a 3 b 4 x 3 y 4 3 RETURN 6 C: D: foo a 3 b 4 x 3 y 4 RETURN 6 ERASE THE FRAME 35

Exercise Time 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> foo(3,4) C: foo Function Call a 3 b 4 x 3 y 4 RETURN 6 What is the next step? 36

Exercise Time 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> foo(3,4) >>> 6 Function Call ERASE THE FRAME 37

Function Access to Global Space All function definitions are in some module Call can access global space for that module math.cos: global for math height.get_feet uses global for height But cannot change values Assignment to a global makes a new local variable! Global Space (for scope_example.py) change_a a 3.5 # scope_example.py """Show how globals work""" a = 4 # global space def change_a(): a a = 3.5 # local variable return a 4 38

Function Access to Global Space All function definitions are in some module Call can access global space for that module math.cos: global for math height.get_feet uses global for height But cannot change values Assignment to a global makes a new local variable! Global Space (for scope_example.py) a 4 get_a # scope_example.py """Show how globals work""" a = 4 # global space def get_a(): return a # returns global 39

Call Frames and Global Variables The specification is a lie: 2 def swap(a,b): """Swap global a & b""" tmp = a a = b b = tmp Global Variables a b 2 Call Frame 3 swap >>> a = >>> b = 2 >>> swap(a,b) a b 2 40

Call Frames and Global Variables The specification is a lie: 2 3 def swap(a,b): """Swap global 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 4

Call Frames and Global Variables The specification is a lie: 2 3 def swap(a,b): """Swap global a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame swap 3 x a 2 b 2 tmp 42

Call Frames and Global Variables The specification is a lie: 2 3 def swap(a,b): """Swap global a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame swap x a 2 b 2 tmp x 43

Call Frames and Global Variables The specification is a lie: 2 3 def swap(a,b): """Swap global a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame ERASE THE FRAME 44

Call Frames and Global Variables The specification is a lie: 2 3 def swap(a,b): """Swap global a & b""" tmp = a a = b b = tmp >>> a = >>> b = 2 >>> swap(a,b) Global Variables a b 2 Call Frame THIS FUNCTION DOES NOT SWAP ERASE THE FRAME the global a and global b 45

Visualizing Frames: The Python Tutor 46

More Exercises Module Text Interactive Python # my_module.py def foo(x): return x+ >>> import my_module >>> my_module.x What does Python give me? x = +2 x = 3*x A: 9 CORRECT B: 0 C: D: Nothing E: Error 47