Week 4: Functions
Class Recordings
To access recordings, sign in with your @swarthmore.edu account.
Monday |
||
Wednesday |
||
Friday |
Announcements
Monday
Substrings, in operator
A substring of a string is a portion of the string that appears contiguously. For example, blue
is a substring of blueberries
. Python has some commands for accessing substrings.
The most relevant for us right now is the in
operator. in
takes a substring called the pattern and another string commonly called the target, and returns True
if and only if the pattern appears as a substring in the target.
Sometimes, the pattern can be a single letter, but in general, the pattern can be any string.
>>> 'a' in "apples" True >>> 'b' in "apples" False >>> "vark" in "Aardvark" True >>> "bbrries" in "blueberries" False
String Formatting
The print statement is nice for outputting, but it is difficult to format the output in a way we prefer. For example, every time we put out a dollar amount, we can’t guarantee two digits after the decimal point for the cents and we also have to always leave a space between the dollar sign and the amount. String formatting allows us to define string templates:
%s |
string value |
%d |
int value |
%f |
float value |
String formatting also enables optional width and precision values:
Feature | Syntax | Example | Semantics |
---|---|---|---|
width |
%<number>type |
%10s |
Format a number to a string with ten spaces minimum. |
precision (float only ) |
%.<number>f |
%.2f |
Require exactly two digits after a decimal point. |
An example, if we print out the float variable pi
from the math library:
>>> from math import pi >>> print(pi) 3.14159265359 >>> print("Pi is %f|" % (pi)) Pi is 3.141593| >>> print("Pi is %.2f|" % (pi)) Pi is 3.14| >>> print("Pi is %20.2f|" % (pi)) Pi is 3.14| >>> print("Pi is %-20.2f|" % (pi)) Pi is 3.14 |
You can combine multiple templates in a single string format:
item = "dozen eggs"
qty = 4
price = 2.79
print("%d %s cost $%.2f" % (qty, item, qty*price) )
While Loops
Another syntactic tool for designing programs in Python is the while
loop.
You’ve previously seen for
loops, Boolean types, and if
statements. The
while
loop is a mix of these three concepts. A typical for
loop executes
for a definite number of times. For example, programmers decide in advance to
loop over things like finite lists, range()
results, or the length of a
string.
What if we are expecting a user to enter input in a specific format (e.g., a
positive integer, a valid date, or a string with no punctuation)? We could
trust the user not to make a mistake, but this approach is not very robust.
Instead, if we detect that a user made a mistake in typing input, we could
prompt the user again. But how many times should we ask? Once? Twice? 100
times? With a for
loop, you’d have to set the number in advance.
A while
loop can solve these types of computational problems by repeatedly
looping until a Boolean condition is met. The general syntax of a while
loop is:
while <CONDITION>: <BODY>
The <CONDITION> is a Boolean expression. When the condition evaluates to
True
, the body of the loop will execute and then re-evaluate the condition.
When the condition finally evaluates to False
, Python skips the body of the
loop and executes the next line after the body.
Note that a for
loop can often be written as an equivalent while
loop.
Let’s look at some examples in while_loops.py
.
While Loop Exercise (challenging)
Practice writing while
loops, using conditional, and formatting strings in a
program called echo.py
. The program should repeatedly prompt the user for an
input string. If the user types anything other than quit
, you should print
their message back with a counter of how many times you’ve "echoed" a message:
$ python3 echo.py
Enter a string: hello
Echo #1: hello
Enter a string: test string
Echo #2: test string
Enter a string: quit
program terminates
Use a while
loop to continue asking the user for strings indefinitely until
they type quit
, and try using string formatting to print the Echo # …
lines.
Wednesday
Functions
Today we’ll introduce another big, key computer science topic: 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:
-
make programs easier to read/understand
-
minimize programmer error
-
put repeated code into functions
-
hide low-level details of a function until you need to understand them.
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 function_examples.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 for each parameter.
Exercise: practice function definition and calls
Practice defining and calling functions by modifying your program in
function_examples.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
.
Friday
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 set values of parameters.
-
Return back to the calling function.
When calling a function, arguments are sometimes but not always plain values. Other times, they are complex expressions. These expressions 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
grabs 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
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):
"""
Computes the sum of values a and b
Returns result
sample usage:
ans = add(3, 4)
print(ans) # Should print: 7
"""
result = a + b
return result
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 average(number1, number2):
toReturn = (number1+number2)/2
return toReturn
def main():
a = 6
b = 11
avg = average(a,b)
print("The average of %d and %d equals %f"%(a,b,avg))
main()
Now, on the whiteboard we’ll see how 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.
-
allocate (place) parameters inside frame
-
allocate local variables for this function here
-
-
The value of each argument is copied to the corresponding parameter in order.
-
Execute called function step-by-step until the return.
-
Send back the return value to calling function.
-
Remove or pop the called function off stack.
-
Continue executing calling function that is now back on top of stack.
Some things to keep in mind as you draw your own stack diagrams:
-
Function call stack is on left, values belong on the right
-
The call stack always grows "up" when we call a function
-
The call stack shrinks when a function returns or reaches the end of its body without a return.
-
There is a separate box on the call stack for each function.
-
Parameters point to the same value as the inputs 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