programmer-defined functions

79
PROGRAMMER-DEFINED FUNCTIONS LECTURE 02-1: CONTROLLING A PROGRAM'S FLOW JIM FIX, REED COLLEGE CSCI 121

Upload: others

Post on 29-Nov-2021

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PROGRAMMER-DEFINED FUNCTIONS

PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: CONTROLLING A PROGRAM'S FLOW

JIM FIX, REED COLLEGE CSCI 121

Page 2: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸

Page 3: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸

Page 4: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸

Page 5: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line.

Page 6: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line.

Page 7: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸ If you ever want to "watch" a Python program, try out The Python Tutor https://pythontutor.com/

▸Using it, you'll see something like this...

Page 8: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸ It also creates named memory slots for each variable that gets introduced. • That named slot stores a calculated value. • A variable's associated value is changed with each assignment statement.

pi: 3.14159global frame

Page 9: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸ It also creates named memory slots for each variable that gets introduced. • That named slot stores a calculated value. • A variable's associated value is changed with each assignment statement.

pi: 3.14159 area: 314.159

global frame

Page 10: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸ It also creates named memory slots for each variable that gets introduced. • That named slot stores a calculated value. • A variable's associated value is changed with each assignment statement.

pi: 3.14159 area: 314.159 radius: 10.0

global frame

Page 11: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸ It also creates named memory slots for each variable that gets introduced. • That named slot stores a calculated value. • A variable's associated value is changed with each assignment statement.

pi: 3.14159 area: 314.159 radius: 10.0

global frame

Page 12: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

RECALL: PYTHON EXECUTION▸ Let's take a look at this script:

pi = 3.14159area = float(input("Circle area? "))radius = (area / pi) ** 0.5print("That circle’s radius is "+str(radius)+".")

▸What we know is that the Python interpreter runs the code, line by line, from the top line to the bottom line. ▸ It also creates named memory slots for each variable that gets introduced. • That named slot stores a calculated value. • A variable's associated value is changed with each assignment statement. ➡ The collection of variable slots of a script is called the global frame

pi: 3.14159 area: 314.159 radius: 10.0

global frame

Page 13: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

"FLOW OF CONTROL"The interpreter goes through the code line-by-line, tracking where it’s at with an instruction pointer.

➡ The movement of that pointer is called the program’s flow of control.

▸When write code with conditional statements and loops, we’ll see program flow that’s not just top to bottom. ➡ Lines might get repeatedly executed, or lines might get skipped.

▸When write our own functions, the interpreter will go somewhere else in the code, and then return back. ➡ The interpreter jumps around in the code.

Page 14: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: BRANCHING▸Here is an example of a conditional (or "if") statement:

pi = 3.14159area = float(input("Circle area? "))if area < 0.0: print("That’s not an area.")else: radius = (area / pi) ** 0.5 print("That circle’s radius is "+str(radius)+".")

▸Depending on the value of area, either the first print or the second print will execute. ➡ The other one will get skipped.

Page 15: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: LOOPING▸Here is an example of a looping "while" statement:

pi = 3.14159area = float(input("Circle area? “))while area < 0.0: area = float(input(“Not an area. Try again:”))radius = (area / pi) ** 0.5print("That circle’s radius is “+str(radius)+”.”)

▸Because of that while statement, the re-prompting and re-input of an area with that second input can be repeatedly executed. ➡ Lines 3 and 4 are repeated until the user enters a good area value.

Page 16: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN▸Python lets us define our own functions. ▸Below is an example with two: getArea and radiusOfCircle.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

Page 17: PROGRAMMER-DEFINED FUNCTIONS

▸Python lets us define our own functions. ▸Below is an example with two: getArea and radiusOfCircle.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 18: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 19: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 20: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 21: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 22: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 23: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 24: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 25: PROGRAMMER-DEFINED FUNCTIONS

▸ The instruction pointer jumps from the main script code, up to the function's code, and then returns back.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 26: PROGRAMMER-DEFINED FUNCTIONS

▸When a function gets called, a local frame gets created for the function's local variables.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

Page 27: PROGRAMMER-DEFINED FUNCTIONS

▸When a function gets called, a local frame gets created for the function's local variables.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

global frame

pi: 3.14159 area: 314.159 radius: 10.0

getArea frame

Page 28: PROGRAMMER-DEFINED FUNCTIONS

▸When a function gets called, a local frame gets created for the function's local variables.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

global frame

a: 314.159 getArea frame

Page 29: PROGRAMMER-DEFINED FUNCTIONS

▸When a function gets called, a local frame gets created for the function's local variables.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

global frame

a: 314.159 getArea frame

Page 30: PROGRAMMER-DEFINED FUNCTIONS

▸When a function gets called, a local frame gets created for the function's local variables.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

global frame

a: 314.159 returning 314.159

getArea frame

Page 31: PROGRAMMER-DEFINED FUNCTIONS

▸When a function gets called, a local frame gets created for the function's local variables.

def getArea(): a = float(input("Circle area? “)) while a < 0.0: a = float(input(“Not an area. Try again:”)) return a

def radiusOfCircle(someArea): from math import pi, sqrt return sqrt(someArea / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

LECTURE 02-1: PYTHON FUNCTIONS

CONTROL FLOW: CALL AND RETURN

area: 314.159global frame

Page 32: PROGRAMMER-DEFINED FUNCTIONS

▸You introduce new functions, and their code, with a def statement. ▸ The code below defines a squaring function:

def square(x): return x * x

▸Here it is in use: >>> square(4)16>>> y = 5>>> square(y)25>>> square(y+2)49

▸ It takes a single value as its parameter. It returns back the square of that value.

LECTURE 02-1: PYTHON FUNCTIONS

PROGRAMMER-DEFINED FUNCTIONS

Page 33: PROGRAMMER-DEFINED FUNCTIONS

▸ The code below computes the distance between two locations on a map: def distanceFromTo(startX, startY, endX, endY): changeX = endX - startX changeY = endY - startY distanceSquared = changeX**2 + changeY**2 return distanceSquared ** 0.5

▸Here it is in use: >>> distanceFromTo(1.5,2,4.5,6)5.0

▸ It takes four values as parameters, and returns a value back.

LECTURE 02-1: PYTHON FUNCTIONS

PROGRAMMER-DEFINED FUNCTIONS

Page 34: PROGRAMMER-DEFINED FUNCTIONS

▸ The code below computes the distance between two locations on a map: def gains(initial, yearly_rate, years): multiplier = 1.0 + yearly_rate / 100.0 growth = multiplier ** years amount = initial * growth return amount - initial

▸Here it is in use: >>> distanceFromTo(1.5,2,4.5,6)5.0>>> gains(100,5,2)10.25>>> print(gains(100,5,1))5.0>>> a0 = 100>>> a1 = a0 + gains(a0,5,1)>>> a2 = a1 + gains(a1,5,1)>>> a2110.25

LECTURE 02-1: PYTHON FUNCTIONS

PROGRAMMER-DEFINED FUNCTIONS

Page 35: PROGRAMMER-DEFINED FUNCTIONS

▸Python reads the functions, looking for its indented lines of code def square(x): return x * x

def gains(initial, yearly_rate, years): multiplier = 1.0 + yearly_rate / 100.0 growth = multiplier ** years amount = initial * growth return amount - initial def distanceFromTo(startX, startY, endX, endY): changeX = endX - startX changeY = endY - startY distanceSquared = changeX**2 + changeY**2 return distanceSquared ** 0.5

LECTURE 02-1: PYTHON FUNCTIONS

INDENTATION

each function's lines are indented by 4 spaces

Page 36: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys

Page 37: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys

33

Page 38: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys

33 9

Page 39: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys

35

Page 40: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys

35 25

Page 41: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys

Page 42: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys5

100

2

Page 43: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys5

100

210.25

Page 44: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys5

100

210.25

3 9

Parameters are fed in.

Page 45: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys5

100

210.25

3 9

Parameters are fed in.A returned result comes out.

Page 46: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS COMPUTE VALUES FROM THEIR PARAMETERS▸A function takes one or more parameter values. ▸ It uses those values to compute its result. ▸ It then returns the result back to the calling expression. ▸Functions can be thought of as “value factories” of a program:

squarex

gainsra0

ys5

100

210.25

3 9

The expected number, type, and ordering of parameters is the function’s interface.

Page 47: PROGRAMMER-DEFINED FUNCTIONS

▸Because functions compute and return a result, they are used within expressions. ▸Can sometimes think of their definitions as being “cut and pasted" in.

For example, the expression>>> square(3) + square(4)

▸ can be viewed as the same as this expression>>> (3 * 3) + (4 * 4)

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTION CALLS AS EXPRESSIONS

Page 48: PROGRAMMER-DEFINED FUNCTIONS

Below gives a template for function definitions: def function-name (parameter-list): lines of statements that compute using the parameters ... return the-computed-value

▸The parameter variables are called its formal parameters. • They don’t have specific values when the function is defined. ▸They represent the values that will get fed in with some call.

➡They vary, in a way, from call to call.

LECTURE 02-1: PYTHON FUNCTIONS

SYNTAX: FUNCTION DEFINITION

Page 49: PROGRAMMER-DEFINED FUNCTIONS

Below gives a template for function definitions: def function-name (parameter-list): lines of statements that compute using the parameters ... return the-computed-value

▸Each line of the function’s body is indented with 4 spaces. ➡This code is executed when the function is called.

▸The last line is often a return statement.

LECTURE 02-1: PYTHON FUNCTIONS

SYNTAX: FUNCTION DEFINITION

Page 50: PROGRAMMER-DEFINED FUNCTIONS

Some more terminology:

▸Below are two calls, or uses, of our square function:

sqrt(square(3) + square(4))

➡Each use of a function occurs at a call site in the code. ➡3 is the actual parameter for its call site. As is 4 for its site.

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTION CALLS

Page 51: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTION CALLSSome more terminology:

▸Below are two calls, or uses, of our square function:

sqrt(square(3) + square(4))

➡Each use of a function occurs at a call site in the code. ➡3 is the actual parameter for its call site. As is 4 for its site.

Page 52: PROGRAMMER-DEFINED FUNCTIONS

▸We typically define functions in scripts.

▸Lay out a series of useful function definitions at the top.

•We call them in the main lines of the script…

• ... but we might perhaps also call them in other functions.

▸If the script has bugs you can load it interactively, then test each function: C02MX1KLFH04:examples jimfix$ python3 -i my_script_with_f.py>>> f(3,4,5) 6789

LECTURE 02-1: PYTHON FUNCTIONS

SCRIPTING WITH FUNCTIONS

Page 53: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

EXAMPLE SCRIPT WITH FUNCTIONSfrom math import pi, sqrt

def getFloat(prompt): return float(input(prompt))

def getArea(): a = getFloat(“Circle area? “) while a < 0.0: a = get_float(“Not an area. Try again: ”) return a

def radiusOfCircle(A): return sqrt(A / pi)

area = getArea()radius = radiusOfCircle(area)print("That circle’s radius is “+str(radius)+”.”)

Page 54: PROGRAMMER-DEFINED FUNCTIONS

Why should we define functions? •Makes code readable. •Creates reusable code components. •Makes debugging and testing easier. •Allows you to hide implementation. With coding its good to take a "client/service" mentality: •Write functions that serve other parts of the code well. • The client code doesn’t need to know the internals of a function, just the

interface.

LECTURE 02-1: PYTHON FUNCTIONS

SCRIPTING WITH FUNCTIONS

Page 55: PROGRAMMER-DEFINED FUNCTIONS

▸Python has the same def syntax for defining procedures ➡ This is my term for a "function that does not return a value." ➡ Instead, it does some stuff, performs some actions.

▸For example def printBoxTop(size): dashes = “-“ * size print(“+” + dashes + “+”) def printBox(width): printBoxTop(width) print(“|” + (“ “*width) + “|”) printBoxTop(width)

▸Below is its use. It's as if we've invented a printBox statement. >>> printBox(4)+----+| |+----+>>>

LECTURE 02-1: PYTHON FUNCTIONS

PROGRAMMER-DEFINED PROCEDURES

Page 56: PROGRAMMER-DEFINED FUNCTIONS

LECTURE 02-1: PYTHON FUNCTIONS

EXAMPLE SCRIPT WITH PROCEDURESdef printBoxTop(size): dashes = “-“ * size print(“+” + dashes + “+”)

def greetTheUser(name): print(“Hi, “ + name + ”. Nice to meet ya!”)

def printBox(w): printBoxTop(w) print(“|” + (“ “ * w) + “|”) printBoxTop(w)

user = input(“What’s your name? “)greetTheUser(user)print(“I’d like to make you a box.”)width = int(input(“How wide of a box would you like? “))printBox(width)print(“Here is one that is twice as wide:”)printBox(width * 2)

Page 57: PROGRAMMER-DEFINED FUNCTIONS

▸In Python, procedures are really just functions. •Python doesn’t distinguish procedures from functions. • This is just my personal dichotomy, from older languages (Pascal, C). ▸“Function”: •A function gets passed some parameters, executes, and then returns a result. •A function is used within an expression. ▸“Procedure”: •A procedure is something that (typically) performs some action/work but does

not return a value. •A procedure is used as a statement. •When a procedure’s work is done, Python continues executing after the line

where it was called. (Control “jumps” then returns.)

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS VS. PROCEDURES

Page 58: PROGRAMMER-DEFINED FUNCTIONS

▸In Python, procedures are really just functions. •Python doesn’t distinguish procedures from functions. • This is just my personal dichotomy, from older languages (Pascal, C). ▸“Function”: •A function gets passed some parameters, executes, and then returns a result. •A function is used within an expression. ▸“Procedure”: •A procedure is something that (typically) performs some action/work but does

not return a value. •A procedure is used as a statement. •When a procedure’s work is done, Python continues executing after the line

where it was called. (Control “jumps” then returns.)

LECTURE 02-1: PYTHON FUNCTIONS

FUNCTIONS VS. PROCEDURES

Page 59: PROGRAMMER-DEFINED FUNCTIONS

▸A function’s code consists of an indented body of statements. ➡ These statements are ones like the top-level ones used in scripts.

▸The function's lines of code compute using the parameter variables. ▸The last line executed is a return statement.

➡It computes a value that gets "handed" back or returned. ▸A function can be called several times within a program’s code.

➡With each call, different values are passed to the function. ▸Procedures are like functions, defined using def.

➡They perform some work but don’t return a value.

LECTURE 02-1: PYTHON FUNCTIONS

SUMMARY

Page 60: PROGRAMMER-DEFINED FUNCTIONS

CONDITIONAL STATEMENTS

LECTURE 02-1: CONTROLLING A PROGRAM'S FLOW

JIM FIX, REED COLLEGE CSCI 121

Page 61: PROGRAMMER-DEFINED FUNCTIONS

▸Python allows us to reason about values and act on them conditionally. ▸For example, consider this function:

def absoluteValueOf(x): if x < 0: return -x else: return x

LECTURE 02-1: CONDITIONAL STATEMENTS

THE "IF-ELSE" CONDITIONAL STATEMENT

Page 62: PROGRAMMER-DEFINED FUNCTIONS

▸Python allows us to reason about values and act on them conditionally. ▸For example, consider this function:

def absoluteValueOf(x): if x < 0: return -x else: return x

▸Below is its use: >>> absoluteValueOf(-5.5) 5.5>>> absoluteValueOf(105.77)105.77>>> absoluteValueOf(0.0)0.0

THE "IF-ELSE" CONDITIONAL STATEMENT LECTURE 02-1: CONDITIONAL STATEMENTS

Page 63: PROGRAMMER-DEFINED FUNCTIONS

▸Python allows us to reason about values and act on them conditionally. ▸For example, consider this function:

def absoluteValueOf(x): if x < 0: return -x else: return x

▸When fed a negative value, it returns the value with its sign flipped. ➡I.e. the positive value with the same magnitude. -5.5 ~> 5.5

▸Otherwise, if positive or 0.0, it just returns that value.

THE "IF-ELSE" CONDITIONAL STATEMENT LECTURE 02-1: CONDITIONAL STATEMENTS

Page 64: PROGRAMMER-DEFINED FUNCTIONS

▸Python allows us to reason about values and act on them conditionally. ▸For example, consider this function:

def absoluteValueOf(x): if x < 0: return -x else: return x

▸When fed a negative value, it returns the value with its sign flipped. ➡I.e. the positive value with the same magnitude. -5.5 ~> 5.5

▸Otherwise, if positive or 0.0, it just returns that value.

THE "IF-ELSE" CONDITIONAL STATEMENT LECTURE 02-1: CONDITIONAL STATEMENTS

Page 65: PROGRAMMER-DEFINED FUNCTIONS

Below gives a template for conditional statements:

if condition-expression: lines of statements executed if the condition holds ... else: lines of statements executed if the condition does not hold ... lines of code executed after, in either case

LECTURE 02-1: CONDITIONAL STATEMENTS

SYNTAX: IF-ELSE STATEMENT

Page 66: PROGRAMMER-DEFINED FUNCTIONS

▸Python allows us to reason about values and act on them conditionally. ▸For example, consider this function:

def absoluteValueOf(x): if x < 0: return -x else: return x

When the function is called, its code gets executed as follows: ▸Python first checks the condition before the colon.

➡ If the condition is True, it executes the first return statement. ➡ If the condition is False, it executes the second return statement.

This is the one sitting under the else line.

CONDITIONAL STATEMENT EXECUTIONLECTURE 02-1: CONDITIONAL STATEMENTS

Page 67: PROGRAMMER-DEFINED FUNCTIONS

Below gives a template for conditional statements:

if condition-expression: lines of statements executed if the condition holds ... else: lines of statements executed if the condition does not hold ... lines of code executed after, in either case

▸Like function def, we use indentation to indicate the "true" block of code and the "false" block of code.

LECTURE 02-1: CONDITIONAL STATEMENTS

SYNTAX: IF-ELSE STATEMENT

Page 68: PROGRAMMER-DEFINED FUNCTIONS

▸Python allows us to reason about values and act on them conditionally. ▸For example, consider this function:

def absoluteValueOf(x): if x < 0: return -x else: return x

▸You could maybe say that if-else gives Python code “intelligence.” ➡ It reasons about the value of x and behaves one way or the other.

▸The code is smart!

CONDITIONAL STATEMENT EXECUTIONLECTURE 02-1: CONDITIONAL STATEMENTS

Page 69: PROGRAMMER-DEFINED FUNCTIONS

▸Here is a procedure that acts differently, depending on the parity of a number.

def reportTheParityOf(n): if n % 2 == 0: print(“even”) else: print(“odd”)

A CONDITIONAL PROCEDURELECTURE 02-1: CONDITIONAL STATEMENTS

Page 70: PROGRAMMER-DEFINED FUNCTIONS

▸Here is a procedure that acts differently, depending on the parity of a number.

def reportTheParityOf(n): if n % 2 == 0: print(“even”) else: print(“odd”)

▸The equality test == is used to compare... • the left-hand expression’s value n % 2 •with the right-hand expression’s value 0. ▸It is used to check whether they are equal.

A CONDITIONAL PROCEDURELECTURE 02-1: CONDITIONAL STATEMENTS

Page 71: PROGRAMMER-DEFINED FUNCTIONS

▸Here is a procedure that acts differently, depending on the parity of a number.

def reportTheParityOf(n): if n % 2 == 0: print(“even”) else: print(“odd”)

▸Below is it in use: >>> reportTheParityOf(3) odd>>> reportTheParityOf(-10)even>>> reportTheParityOf(0)even

A CONDITIONAL PROCEDURELECTURE 02-1: CONDITIONAL STATEMENTS

Page 72: PROGRAMMER-DEFINED FUNCTIONS

▸ The full range of comparisons you can make are:

== equality != inequality < less than > greater than >= greater than or equal <= less than or equal

COMPARISON OPERATIONSLECTURE 02-1: CONDITIONAL STATEMENTS

Page 73: PROGRAMMER-DEFINED FUNCTIONS

▸ The function below determines whether an integer rating is from 1 to 10: def assessRating(rating): if (rating > 0) and (rating <= 10): return rating else: return “not a rating”

▸Below is it in use: >>> assessRating(3) 3>>> assessRating(11)"not a rating"

EXPRESSING COMPLEX CONDITIONSLECTURE 02-1: CONDITIONAL STATEMENTS

Page 74: PROGRAMMER-DEFINED FUNCTIONS

▸ The function below determines whether an integer rating is from 1 to 10:

def assessRating(rating): if (rating > 0) and (rating <= 10): return rating else: return “not a rating”

▸This is using the logical connective and to check whether both conditions hold. This is their logical conjunction.

EXPRESSING COMPLEX CONDITIONSLECTURE 02-1: CONDITIONAL STATEMENTS

Page 75: PROGRAMMER-DEFINED FUNCTIONS

▸ The function below determines whether an integer rating is from 1 to 10:

def assessRating(rating): if (rating > 0) and (rating <= 10): return rating else: return “not a rating”

▸This is using the logical connective and to check whether both conditions hold. This is their logical conjunction. ▸There is also the connective or for checking whether at least one condition

holds. It described logical disjunction.

EXPRESSING COMPLEX CONDITIONS: ANDLECTURE 02-1: CONDITIONAL STATEMENTS

Page 76: PROGRAMMER-DEFINED FUNCTIONS

▸ The function below determines whether an integer rating is from 1 to 10:

def assessRating(rating): if (rating <= 0) or (rating > 10): return “not a rating” else: return rating

▸This is using the logical connective and to check whether both conditions hold. This is their logical conjunction. ▸There is also the connective or for checking whether at least one condition

holds. It described logical disjunction.

EXPRESSING COMPLEX CONDITIONS: ORLECTURE 02-1: CONDITIONAL STATEMENTS

Page 77: PROGRAMMER-DEFINED FUNCTIONS

▸ The function below determines whether an integer rating is from 1 to 10:

def assessRating(rating): if not ((rating <= 0) or (rating > 10)): return rating else: return “not a rating”

▸This is using the logical connective and to check whether both conditions hold. This is their logical conjunction. ▸There is also the connective or for checking whether at least one condition

holds. It described logical disjunction. ▸There is also logical negation using not.

EXPRESSING COMPLEX CONDITIONS: ORLECTURE 02-1: CONDITIONAL STATEMENTS

Page 78: PROGRAMMER-DEFINED FUNCTIONS

SUMMARY▸We introduce function and procedure definitions using the def statement.

▸Functions take parameters and compute a value, they hand that value back to the calling code with the return statement.

➡ Functions are called within expressions.

▸Procedures take parameters and perform an action.

➡ Procedures are called as a program statement.

▸The if-else statment is used to conditionally execute code.

•Comparison operations: == != < > <= >=

• Logic connectives: and or not

LECTURE 02-1: CONDITIONAL STATEMENTS

Page 79: PROGRAMMER-DEFINED FUNCTIONS

ASSIGNMENT AND READING▸Again, don't forget you have CSCI 121 lab tomorrow!

▸We'll have a lab Homework 2 assignment:

• assigned tomorrow, due next Wednesday 9/15, before lecture

• the description will be at https://jimfix.github.io/csci121/assign.html

• you'll write several Python functions much like these examples

▸Reading for today's material:

✦ TP Ch. 3, 5 (functions); TP Chs 4.1-4.8 (conditionals)

✦CP 1.3-1.4

LECTURE 01-2: PYTHON SCRIPTING