Week 4: while loops and functions
Week 4 Goals
-
Learn to use
while
statements to create indefinite loops -
Learn how the
randrange
function can pick random integers -
Learn to write your own functions
-
Learn how function call arguments are passed to function parameters
-
Learn to use the return statement to send a value back to the calling function
-
Learn to how python uses a call stack to keep track of function calls
-
Learn about variable scope and how it relates to the call stack
Week 4 Code
-
while_loops.py
: practice with while-loops -
guess.py
: play a number guessing game -
greet.py
: example of program with multiple functions -
stars.py
: examples of functions that print stars -
rectangle.py
: write functions to compute the area and perimeter of a rectangle -
circle.py
: write functions to compute the area and circumference of a circle
Week 4 Concepts
-
While loops
-
Importing from modules; generating random numbers
-
Functions
while
loops
One limitation of for-loops is that we need to know in advance how many times the loop will run, based on the number of values in the sequence over which we’re iterating.
If we don’t know in advance how many times the loop should run, but want to keep looping as long as some condition is true, an alternative is to use a while loop, which will keep looping until the condition is false.
For instance, this code keeps looping while the value
is negative or
zero, and stops looping once the user enters a positive value:
value = -1
while (value <= 0):
value = int(input("Please enter a positive number: "))
print("the number is " + str(value))
Once we exit the loop, we know that value must be positive, otherwise we’d still be looping!
The file while_loops.py
in the week 4 inclass directory demonstrates
a three examples of while
loops. Two of them are incomplete and will
need you to fix them.
The file guess.py
plays a number guessing game. As implemented,
the game isn’t very fun, but you can make it more fun!
Importing from modules
Python automatically provides several built-in functions and the
ability to import functions and variables from other modules. One
example is the random
module.
# place your imports at the top of the program before def main()
from random import randrange
# you can now use randrange function to generate random numbers
In the guess.py
example, we use randrange
to generate the
secret number that the user is trying to guess.
Functions
Another big, key computer science topic is functions.
A function is a named sequence of statements that
perform a particular operation. Some functions are built in
(int,str,float,input,print
), but you can also define your own
functions. Defining your own functions has many benefits:
-
Modularity and Readability: break program up into functional parts, make programs easier to read/understand/debug.
-
Abstraction: hide low-level details of a function until you need to understand them; you can use a function without having to know how it is implemented (e.g., the
print
function). -
Code Reuse: put repeated code into functions: "write code once, use function multiple times".
-
Minimize programmer error: write and test functions in isolation.
In fact, you’ve been defining and using your own functions for a
couple of weeks now, with the main()
function. This week, we’ll see
many more examples of functions. You’ll see that functions can take
input and return input, and even do other "side effects" in between.
Function Syntax
Here is the syntax for how to define a function:
def <name>(<parameters>):
<body>
The <name>
is the name of the function you define. The <body>
is
a series of statements that you want to execute each time you use your
function. <parameters>
is a list of zero or more inputs to the
function. These parameters can be used inside the function just like
any other variable.
Let’s look at some examples in stars.py
. We have defined four
functions so far: printIntro, printStarRow(n), starBox(n)
, and
main()
. We will describe a few of these and then have you practice
some.
Once a function is defined, you can call the function, by giving the name of the function and specific values ("arguments") for each parameter.
Exercise: practice function definition and calls
Practice defining and calling functions by modifying your program in
stars.py
to implement starBox(n)
. Call starBox
in main
with
different values of n
. Try getting a value from the user with
input
in main
and passing the value to starBox
.
What happens when a function gets called?
Python does a lot of behind-the-scenes work when a function gets called. Here is an outline of what happens:
Steps that occur when a function is called:
-
Suspend current function.
-
Evaluate arguments, copy them to parameters of the called function in order.
-
Execute called function using the values of the parameters.
-
Return back to the calling function.
When calling a function, arguments are expressions that get evaluated in Step 2 of the process above.
starBox(2**3)
The return
statement.
Often when you define a function, you want the function to return some
value back to whatever program called the function. You can do this
with the return
command. For example, the built-in function input
reads in a string of text from the user and returns it as a string.
When a return statement is reached, the function stops and immediately
returns the value indicated by the return statement.
For example, if you defined a function def add(a,b)
to add the
values a
and b
integers, you’ll probably want to define and return
a variable that stores the result, for example result=a+b
. Then,
once you’ve added the numbers, the return result
statement sends
this value back to the calling function.
def add(a, b):
"""
Adds two numbers together and returns the result
Args:
a (int): the first number to add
b (int): the second number to add
Returns:
int: the sum of a and b
"""
return a + b
Exercise: functions for area and circumference of a circle
In the rectangle.py
file, we will write the area_rectangle
and
perimeter_rectangle
functions.
Can you adapt these solutions to the circle.py
file? What types do
you want here for the radius, area, and circumference? Can you display
the output nicely using string formatting?
Stack Diagrams
A stack diagram is a way to visualize what happens with variables in memory as Python executes your program. Consider the following program:
def main():
a = 6
b = 11
avg = average(a,b)
print("The average of %d and %d equals %.1f" % (a, b, avg))
def average(num1, num2):
"""
computes the average of two numeric values
param num1: one value
param num2: the other value
returns: the average of the two values
"""
to_return = (num1 + num2)/2
return to_return
main()
This computation happens in memory. The computer’s memory is where the program stores the state of a running program including the values of all variables and the stack of all functions currently waiting to finish. Here is the general procedure for how a function execute when called:
-
Pause the execution of the current function.
-
Create a stack frame for the called function.
-
space for parameters are allocated in the function’s stack frame
-
space for local variables are allocated in the function’s stack frame
-
-
Each argument’s value is passed to the corresponding parameter: the value of each argument (the reference in the box) is copied to the corresponding parameter in order. For example, the third parameter refers to the same value of as the third argument.
-
Execute called function step-by-step until the return or until it reaches the end of the function body.
-
Send back the return value to calling function.
-
Remove or pop the called function’s frame off stack.
-
Continue executing calling function that is now back on top of stack. (the called function now evaluates to its return value in the caller)
Some things to keep in mind as you draw your own stack diagrams:
-
Function call stack is on left, values belong on the right
-
Space for variables and parameters are inside stack frames, the values to which they refer are outside the stack
-
The call stack always grows "up" when we call a function
-
The call stack shrinks when a function returns.
-
There is a separate box (frame) on the call stack for each function.
-
Parameters point to the same value as the arguments in the calling function.
-
The assignment operator changes the arrow.
-
A function can only access/reference variable names in its own stack frame. These variables are said to be in the function’s scope
Try: Stack Example
def main():
x = 5
y = 9
ans = add_numbers(x,y)
print("In main:")
print(ans)
print(total) # Q2b: Gives an error. Q: Why?
def add_numbers(num1,num2):
"""
adds two numbers together
param num1: one value
param num2: the other value
returns: sum of num1 and num2
"""
total = num1 + num2
print("In add_numbers:")
print(num1)
print(num2)
print(total)
# Q1: Show the stack diagram as it exists at this point
return total
main()
-
Draw the stack up to the point right before
return total
is executed -
Answer the following questions:
-
(a) What is the scope, respectively, of
x
,y
,ans
,num1
,num2
, andtotal
? -
(b) Why does the last line of
main()
give a runtime error?
-