Week 4: Functions

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.

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 %d" % (value))

Once we exit the loop, we know that value must be positive, otherwise we’d still be looping!

Let’s look at some examples in while_loops.py.

Note that a for loop can often be written as an equivalent while loop.

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 randint

# you can now use randint function to generate random numbers

In the guess.py example, we use randint to generate the secret number that the user is trying to guess.

As implemented, the game isn’t very fun, but you can make it more fun!

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: print_intro, print_star_row(n), print_star_box(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 print_star_box(n). Call print_star_box in main with different values of n. Try getting a value from the user with input in main and passing the value to print_star_box.

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:

  1. Suspend current function.

  2. Evaluate arguments, copy them to parameters of the called function in order.

  3. Execute called function using set values of parameters.

  4. 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.

print_star_box(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

Exercise: functions for area and perimeter of a rectangle

In the rectangle.py file, we will write the area_rectangle and perimeter_rectangle functions.

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 executes when called:

  1. Pause the execution of the current function.

  2. Create a stack frame for the called function.

    • allocate (place) parameters inside frame

    • allocate local variables for this function here

  3. The value of each argument is copied to the corresponding parameter in order.

  4. Execute called function step-by-step until the return.

  5. Send back the return value to calling function.

  6. Remove or pop the called function off stack.

  7. 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.

Stack Example 2

def add_numbers(num1,num2):
  total = num1 + num2
  print("In add_numbers:")
  print(num1)
  print(num2)
  print(total)

  #Show the stack diagram as it exists at this point
  return total

def main():

  x = 5
  y = 9

  ans = add_numbers(x,y)
  print("In main:")
  print(ans)
  print(total) #Gives an error. Why?

main()

Answer the following questions:

  • What is the scope, respectively, of x, y, ans, num1, num2, and total?

  • Why does the last line of main() give a runtime error?

Stack Example 3

Try another example of stack drawing.

def absval(x,y):
  if x > y:
    aval = x-y
  else:
    aval = y-x

  # draw stack to this point!
  # as it would look just before return...

  return aval

def main():
  a = 10
  b = 35
  result = absval(a,b)
  print("abs(%d-%d) = %d" % (a,b,result))

main()

Exercise: total

In totally.py, define a function total(n), which takes a positive integer as input and returns the sum of the first n positive integers. Then, call your function on several different inputs.

Strings and Mutability

We know of several string features so far. Assuming s is a string variable:

  • len(s) to get the length of the string.

  • s + "more characters" to concatenate strings.

  • s * 3 to repeat a string multiple times.

  • Strings can be compared with relational operators (e.g., <, >, ==).

  • s[i] to index into the string and access the ith character.

While strings support indexing with brackets ([]), Python does not allow you to change the value in a position — the indices are read-only. For example:

>>> name = "Kevin"

# Normal indexing works fine for reading characters.
>>> name[1]
'e'

# Can't modify characters.
>>> name[1] = "a"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

Because strings allow reading but not writing, they’re said to be immutable. That is, their contents cannot be mutated (changed). Coming up soon, we’ll start to see data types that are mutable!