Week 4: while loops and functions

Week 4 Goals

  • Learn the % operator for formatting strings

  • 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

Week 4 Code

  • template.py: a short example of using string formatting

  • string_format.py: examples using width and precision

  • mi_km_fmt.py: formatting our miles to kilometers table

  • while_loops.py: practice with while-loops

  • guess.py: play a number guessing game

  • stars.py: examples of functions that print stars

  • old_mac.py and old_mac_fn.py: using functions for code re-use

  • rectangle.py: compute the area and perimeter of a rectangle

  • circle.py: compute the area and circumferce of a circle

Week 4 Concepts

  • String formatting

  • While loops

  • Importing from modules

  • Functions

String formatting

Until now we have been using string concatenation to dynamically generate strings:

name = input("Enter your name: ")
age = input("Enter your age: ")
next_age = int(age) + 1
print("Hi, " + name + ", nice to meet you." + \
    "You'll turn " + next_age + " on your next birthday!")

This can become cumbersome and error-prone when we have strings that require lots of concatenation, so a more concise way is to use the string formatting operator %, which takes a template (or "format") string and then replaces placeholder terms with specific values:

name = input("Enter your name: ")
age = input("Enter your age: ")
next_age = int(age) + 1
format = "Hi, %s, nice to meet you. You'll turn %d on your next birthday!"
msg = format % (name, next_age)
print(msg)

In the format string, the %s is a placeholder for a string, and %d is the placeholder for a decimal (base-10) integer. The value of the msg variable is created by applying the values of name and next_age to the template.

We can also use string formatting to indicate how much space a string should take when being displayed, e.g. by adding spaces before or after it, or the precision (number of values after the decimal point) of a floating point value:

num = 2.718281828
print("the number is %.3f" % (num) ) # prints "the number is 2.718"

In the above example, the %.3f indicates this is a placeholder for a floating point number and that we want to display three values after the decimal point.

There are two files in the week 4 inclass directory:

  • The template.py file contains a small example demonstrating how you can include int, float and str data into your output using string formatting.

  • The string_format.py file shows how you can use more advanced features of string formatting to control the width and precision of the data you are including in your strings.

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:

  1. Suspend current function.

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

  3. Execute called function using the values of the parameters.

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

Functions for code re-use

Compare the old_mac.py and old_mac_function.py files to see how using functions can allow us to re-use code without needing to copy-and-paste the same code over and over in our program.

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?