Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic...

32
Defining Functions Lecture 3

Transcript of Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic...

Page 1: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Defining Functions

Lecture 3

Page 2: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Announcements for this Lecture

Reminder

• Quiz: Academic Integrity• Take it by tomorrow• Also remember survey

Assignment 1

• Assignment 1 is live§ Posted on web page§ Due Fri, Sep. 26th

§ Revise up to a week• Lab 2 will help a lot

§ Testing is a major part § Try to finish it first§ But start A1 early!

9/14/15 Objects 2

Page 3: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

We Write Programs to Do Things

• Functions are the key doers

9/14/15 Objects 3

Function Call Function Definition• Command to do the function

greet('Walker')

• Defines what function does

def greet(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

Page 4: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

We Write Programs to Do Things

• Functions are the key doers

9/14/15 Objects 4

Function Call Function Definition• Command to do the function

greet('Walker')

• Defines what function does

def greet(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

FunctionHeader

Page 5: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

We Write Programs to Do Things

• Functions are the key doers

9/14/15 Objects 5

Function Call Function Definition• Command to do the function

greet('Walker')

• Defines what function does

def greet(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

FunctionHeader

FunctionBody

(indented)

Page 6: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

We Write Programs to Do Things

• Functions are the key doers

9/14/15 Objects 6

Function Call Function Definition• Command to do the function

greet('Walker')

• Defines what function does

def greet(n):print 'Hello '+n+'!'

declaration of parameter 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

FunctionHeader

FunctionBody

(indented)

Page 7: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

We Write Programs to Do Things

• Functions are the key doers

9/14/15 Objects 7

Function Call Function Definition• Command to do the function

greet('Walker')

• Defines what function does

def greet(n):print 'Hello '+n+'!'

declaration of parameter n

argument to assign to 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

FunctionHeader

FunctionBody

(indented)

Page 8: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Anatomy of a Function Definition

def greet(n):"""Prints a greeting to the name n

Parameter n: name to greet Precondition: n is a string"""

print 'Hello '+n+'!'print 'How are you?'

9/14/15 Objects 8

Function Header

name parameters

DocstringSpecification

Statements to execute when called

Page 9: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Anatomy of a Function Definition

def greet(n):"""Prints a greeting to the name n

Parameter n: name to greet Precondition: n is a string"""

print 'Hello '+n+'!'print 'How are you?'

9/14/15 Objects 9

Function Header

name parameters

DocstringSpecification

Statements to execute when called

The vertical line indicates indentation

Page 10: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

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,1)

9/14/15 Objects 10

Historical Aside• Historically “function” = “fruitful function”• But now we use “function” to refer to both

Page 11: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

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 functiondef to_centigrade(x):

"""Returns: x converted to centigrade"""return 5*(x-32)/9.0

9/14/15 Objects 11

Page 12: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Print vs. Return

Print

• Displays a value on screen§ Used primarily for testing§ Not useful for calculations

def print_plus(n):print (n+1)

>>> x = plus_one(2)3>>>

Return

• Defines a function’s value§ Important for calculations§ But does not display anything

def return_plus(n):return (n+1)

>>> x = plus_one(2)>>>

9/14/15 Objects 12

Page 13: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Print vs. Return

Print

• Displays a value on screen§ Used primarily for testing§ Not useful for calculations

def print_plus(n):print (n+1)

>>> x = plus_one(2)3>>>

Return

• Defines a function’s value§ Important for calculations§ But does not display anything

def return_plus(n):return (n+1)

>>> x = plus_one(2)>>>

9/14/15 Objects 13

x 3x

Nothing here!

Page 14: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Module Example: Temperature Converter# temperature.py"""Conversion functions between fahrenheit and centrigrade"""

# Functionsdef 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

# ConstantsFREEZING_C = 0.0 # temp. water freezes…9/14/15 Objects 14

Style Guideline:Two blank lines betweenfunction definitions

Page 15: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

String Parsing Example

def second_in_list(s):"""Returns: second item in comma-separated list

The final result does not have any whitespace on edges

Precondition: s is a string of items separated by a comma."""startcomma = s.index(',')tail = s[startcomma+1:]endcomma = tail.index(',')item = tail[:endcomma].strip()return item

9/14/15 Objects 15

See commalist.py

Page 16: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Recall: The Python API

9/14/15 Objects 16

Function name

Number of arguments

What the function evaluates to

• This is a specification§ Enough info to use func.§ But not how to implement

• Write them as docstrings

Page 17: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Anatomy of a Specification

def greet(n):"""Prints a greeting to the name n

Greeting has format 'Hello <n>!'Followed by conversation starter.

Parameter n: person to greetPrecondition: n is a string"""print 'Hello '+n+'!’print 'How are you?'

9/14/15 Objects 17

One line description,followed by blank line

Page 18: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Anatomy of a Specification

def greet(n):"""Prints a greeting to the name n

Greeting has format 'Hello <n>!'Followed by conversation starter.

Parameter n: person to greetPrecondition: n is a string"""print 'Hello '+n+'!’print 'How are you?'

9/14/15 Objects 18

One line description,followed by blank line

More detail about the function. It may be many paragraphs.

Page 19: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Anatomy of a Specification

def greet(n):"""Prints a greeting to the name n

Greeting has format 'Hello <n>!'Followed by conversation starter.

Parameter n: person to greetPrecondition: n is a string"""print 'Hello '+n+'!’print 'How are you?'

9/14/15 Objects 19

One line description,followed by blank line

More detail about the function. It may be many paragraphs.

Parameter description

Page 20: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Anatomy of a Specification

def greet(n):"""Prints a greeting to the name n

Greeting has format 'Hello <n>!'Followed by conversation starter.

Parameter n: person to greetPrecondition: n is a string"""print 'Hello '+n+'!’print 'How are you?'

9/14/15 Objects 20

One line description,followed by blank line

More detail about the function. It may be many paragraphs.

Parameter description

Precondition specifies assumptions we make about the arguments

Page 21: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

One line description,followed by blank line

Anatomy of a Specification

def to_centigrade(x):"""Returns: x converted to centigrade

Value returned has type float."""

Parameter x: temp in fahrenheitPrecondition: x is a floatreturn 5*(x-32)/9.0

9/14/15 Objects 21

More detail about the function. It may be many paragraphs.

Parameter description

Precondition specifies assumptions we make about the arguments

Page 22: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

One line description,followed by blank line

Anatomy of a Specification

def to_centigrade(x):"""Returns: x converted to centigrade

Value returned has type float.

Parameter x: temp in fahrenheitPrecondition: x is a float"""return 5*(x-32)/9.0

9/14/15 Objects 22

“Returns” indicates afruitful function

More detail about the function. It may be many paragraphs.

Parameter description

Precondition specifies assumptions we make about the arguments

Page 23: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Preconditions

• Precondition is a promise§ If precondition is true,

the function works§ If precondition is false,

no guarantees at all• Get software bugs when

§ Function precondition is not documented properly

§ Function is used in ways that violates precondition

>>> to_centigrade(32)0.0>>> to_centigrade(212)100.0

9/14/15 Objects 23

Page 24: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Preconditions

• Precondition is a promise§ If precondition is true,

the function works§ If precondition is false,

no guarantees at all• Get software bugs when

§ Function precondition is not documented properly

§ Function is used in ways that violates precondition

>>> to_centigrade(32)0.0>>> to_centigrade(212)100.0>>> to_centigrade('32')Traceback (most recent call last):File "<stdin>", line 1, in <module>File "temperature.py", line 19 …

TypeError: unsupported operand type(s) for -: 'str' and 'int'

9/14/15 Objects 24

Precondition violated

Page 25: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Test Cases: Finding Errors• Bug: Error in a program. (Always expect them!)• Debugging: Process of finding bugs and removing them. • Testing: Process of analyzing, running program, looking for bugs.• Test case: A set of input values, together with the expected output.

def number_vowels(w):"""Returns: number of vowels in word w.

Precondition: w string w/ at least one letter and only letters"""pass # nothing here yet!

9/14/15 Objects 25

Get in the habit of writing test cases for a function from the function’s specification —even before writing the function’s body.

Page 26: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Test Cases: Finding Errors• Bug: Error in a program. (Always expect them!)• Debugging: Process of finding bugs and removing them. • Testing: Process of analyzing, running program, looking for bugs.• Test case: A set of input values, together with the expected output.

def number_vowels(w):"""Returns: number of vowels in word w.

Precondition: w string w/ at least one letter and only letters"""pass # nothing here yet!

9/14/15 Objects 26

Get in the habit of writing test cases for a function from the function’s specification —even before writing the function’s body.

Some Test Cases§ number_vowels('Bob')

Answer should be 1§ number_vowels('Aeiuo')

Answer should be 5§ number_vowels('Grrr')

Answer should be 0

Page 27: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Representative Tests

• Cannot test all inputs§ “Infinite” possibilities

• Limit ourselves to tests that are representative§ Each test is a significantly

different input§ Every possible input is

similar to one chosen• An art, not a science

§ If easy, never have bugs§ Learn with much practice

9/14/15 Objects 27

Representative Tests fornumber_vowels(w)

• Word with just one vowel§ For each possible vowel!

• Word with multiple vowels§ Of the same vowel§ Of different vowels

• Word with only vowels• Word with no vowels

Page 28: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Running Example• The following function has a bug:

def last_name_first(n):"""Returns: copy of <n> but in the form <last-name>, <first-name>

Precondition: <n> is in the form <first-name> <last-name> with one or more blanks between the two names"""end_first = n.find(' ')first = n[:end_first]last = n[end_first+1:]return last+', '+first

• Representative Tests:§ last_name_first('Walker White') give 'White, Walker'§ last_name_first('Walker White') gives 'White, Walker'

9/14/15 Objects 28

Look at preconditionwhen choosing tests

Page 29: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Unit Test: A Special Kind of Module

• A unit test is a module that tests another module§ It imports the other module (so it can access it)§ It imports the cornelltest module (for testing)§ It defines one or more test procedures

• Evaluate the function(s) on the test cases• Compare the result to the expected value

§ It has special code that calls the test procedures• The test procedures use the cornelltest function

def assert_equals(expected,received):"""Quit program if expected and received differ"""

9/14/15 Objects 29

Page 30: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Modules vs. Scripts

Module

• Provides functions, constants§ Example: temp.py

• import it into Python§ In interactive shell…§ or other module

• All code is either§ In a function definition, or§ A variable assignment

Script

• Behaves like an application§ Example: helloApp.py

• Run it from command line§ python helloApp.y§ No interactive shell§ import acts “weird”

• Commands outside functions§ Does each one in order

9/14/15 Objects 30

Page 31: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Testing last_name_first(n)

# test proceduredef test_last_name_first():

"""Test procedure for last_name_first(n)"""result = name.last_name_first('Walker White')cornelltest.assert_equals('White, Walker', result)result = name.last_name_first('Walker White') cornelltest.assert_equals('White, Walker', result)

# Execution of the testing codetest_last_name_first()print 'Module name is working correctly'

9/14/15 Objects 31

Quits Pythonif not equal

Message will print out only if no errors.

Page 32: Lecture 3 - Cornell University · Announcements for this Lecture Reminder • Quiz: Academic Integrity • Take it by tomorrow • Also remember survey Assignment 1 • Assignment

Testing last_name_first(n)

# test proceduredef test_last_name_first():

"""Test procedure for last_name_first(n)"""result = name.last_name_first('Walker White')cornelltest.assert_equals('White, Walker', result)result = name.last_name_first('Walker White') cornelltest.assert_equals('White, Walker', result)

# Execution of the testing codetest_last_name_first()print 'Module name is working correctly'

9/14/15 Objects 32

Quits Pythonif not equal

Message will print out only if no errors.

Call function on test input

Compare to expected output