Old version
This is the CS 111 site as it appeared on May 10, 2018.
Lab 7: Loops
Task 0: practice tracing loops
-
Trace the following program using a table, and determine the output:
values = [7, 2, 5, 3, 8] for i in range(len(values)): if values[i] % 2 == 1: values[i] = -1 * values[i] print(values)
Here’s the beginning of the table:
i
values[i]
action taken (if any) 0
7
values[0] = -1*7 = -7
... Follow-up questions:
-
What is the output of this program?
-
Rewrite this program so that it uses a
while
loop instead of afor
loop. The revised program should process the list in the same way as the original program. Here’s a template you can use:values = [7, 2, 5, 3, 8] i = 0 while __________________: if values[i] % 2 == 1: values[i] = -1 * values[i] ______________________ print(values)
-
At the end of the lab, you should turn in your paper trace to the TF. To get credit for attendance at today’s lab, you must have made a good effort on this trace.
Task 1: write functions that use a loop
Warning
When working with Python on the lab machines, make sure that you use a version of Python 3. Do not use a version of Python 2.
In IDLE, use the File -> New Window menu option to open a new editor
window, and save it using the name lab7task1.py
.
The manager of the Boston Bruins hockey team has asked us to write a program that will analyze the team’s results. These results will be represented by two lists of integers:
-
one list containing the goals scored by the Bruins in each of a series of games
-
one list containing the goals scored by their opponents in those same games.
For example, here is one possible set of results:
bruins_goals = [1, 4, 3] opponent_goals = [2, 1, 3]
Looking at these lists, we see that:
-
The Bruins lost the first game 1-2, because there is a 1 in position 0 of their list of goals, and a 2 in position 0 of their opponent’s list of goals.
-
The Bruins won the second game 4-1, because there is a 4 in position 1 of their list of goals, and a 1 in position 1 of their opponent’s list of goals.
-
The Bruins tied the third game 3-3, because there is a 3 in position 2 of both lists of goals.
In this task, we’ll begin to implement some of the functionality that our program for the Bruins will need. We’ll do so by writing a series of functions, each of which uses a loop to process one or more lists of goals.
-
Copy the following template into your file.
def find_max_goals(goals): """ returns the largest number of goals in the specified list of goals, which we assume contains at least one integer """ maxg = goals[0] for g in goals: if ________________: ___________________ return _____
Replace the blanks with the code needed to create a function that takes a list of one or more integers containing the goals scored by a team, and that returns the maximum number of goals in that list. You may not use the built-in
max()
function.Hints:
-
The loop in our template is an element-based
for
loop. Given that fact, what values will the variableg
take on? -
You should use the variable
maxg
to keep track of the largest number of goals that you have seen thus far.
-
-
Write a function
find_num_wins(bruins, opponents)
that takes two lists of integers containing the goals scored by the Bruins and their opponents (see above), and that returns the number of games that the Bruins won.For example:
>>> find_num_wins([1, 4, 3], [2, 1, 3]) # won the second game 1 >>> find_num_wins([1, 4, 3, 5], [2, 1, 3, 2]) # won second and fourth games 2
Hints:
-
This problem is best solved using an index-based
for
loop. Why? -
This is a cumulative computation, so you will need to initialize an accumulator variable before the loop, and then increment the accumulator as needed within the body of the loop.
-
-
Write a function
print_results(bruins, opponents)
that takes two lists of integers containing the goals scored by the Bruins and their opponents (see above), and that prints the results of each game in the format shown below. The function should not return a value.Here are two examples of what the format should look like:
>>> print_results([1, 4, 3], [2, 1, 3]) loss 1-2 win 4-1 tie 3-3 >>> print_results([5, 3, 2, 1], [2, 1, 2, 4]) win 5-2 win 3-1 tie 2-2 loss 1-4
Before you begin coding, ask yourself which type of
for
loop makes the most sense here: element-based or index-based?Hint: To print the score for a given game, you’ll need to:
-
use string concatenation so that there will be no spaces between the numbers and the hyphen (
-
) -
use the
str()
function to turn each team’s number of goals into a string, so that you can then concatenate it.
-
Task 2: complete an interactive program
Although the functions from Task 1 are useful on their own, the Bruins want us to give them an interactive program so that they won’t need to remember how the functions work.
In lab7task2.py
, we’ve given you
some starter code for this interactive program.
Download that file now and open it in IDLE.
Reviewing the starter code
The starter code includes several functions:
-
one called
display_menu()
that prints a menu of options to the user -
one called
latest_score()
that returns the score of the latest (i.e., most recent) game -
one called
main()
that is used to start the program, and to repeatedly carry out tasks selected by the user
Let’s start by reviewing the main()
method together. Among other things,
we should answer the following questions:
-
What is the purpose of the
while
loop inmain()
? -
What is the purpose of the following line of code?
choice = int(input('Enter your choice: '))
-
What is the purpose of the
if-elif-else
statement inmain()
? -
What happens when the user enters a value of 0 for
choice
? -
What happens when the user enters a value of 1 for
choice
? -
When does the
while
loop end?
Running the program
To run the program, you should:
-
Run
lab7task2.py
in IDLE, which you will bring you to the Shell. -
Call the
main()
function:>>> main()
At the moment, the only supported menu choices are 0 and 1, so go ahead and try executing each of those choices.
Adding support for choices 2-4
In Task 1, you already wrote the functions needed for choices 2-4.
To incorporate them into the program, you should:
-
Copy your functions from Task 1 into
lab2task2.py
. -
In
main()
, add a newelif
block for each of these choices. Here is a reminder of the relevant section of the menu:2) Print the results 3) Find the number of wins 4) Find the max number of goals
Make sure that your new
elif
blocks go in between the existingelif
blocks and theelse
block. -
In each case, the
elif
block for a given choice should begin by making an appropriate function call to one of your functions from Task 1. -
If the function that you call for a given choice returns a value, store that value in a variable, and use that variable to print an appropriate message to the user. See our implementation of choice 1 for an example of this.
-
If the function that you call for a given choice doesn’t return a value, you can simply call the function, and you won’t need to do anything after it returns.
A sample run that illustrates what the behavior of the program should look like is available here.
Adding support for new functionality
The Bruins would also like your program to be able to compute their
complete record – i.e., their number of wins, losses, and ties.
This new functionality will be menu choice 5.
Write an appropriate separate function for choice 5. Your function
should take whatever inputs is needs, and it should return the record
as a list of the form [wins, losses, ties]
.
Once your function is working, add a new elif
block for it in main()
,
and update the display_menu()
function to add the choice to the
menu.
Task 3: submit your work
You should turn in the paper with your work on Task 0 to the teaching fellow.
You should use Apollo to submit your lab7task1.py
and lab7task2.py
files.
Don’t worry if you didn’t finish all of the tasks. You should just submit whatever work you were able to complete during lab.
Here are the steps:
- Login to Apollo, using the link in the left-hand navigation bar. You will need to use your Kerberos user name and password.
- Check to see that your BU username is at the top of the Apollo page. If it isn’t, click the Log out button and login again.
- Find the appropriate lab section on the main page and click Upload files.
- For each file that you want to submit, find the matching upload section for the file. Make sure that you use the right section for each file. You may upload any number of files at a time.
- Click the Upload button at the bottom of the page.
- Review the upload results. If Apollo reports any issues, return to the upload page by clicking the link at the top of the results page, and try the upload again, per Apollo’s advice.
- Once all of your files have been successfully uploaded, return to the upload page by clicking the link at the top of the results page. The upload page will show you when you uploaded each file, and it will give you a way to view or download the uploaded file. Click on the link for each file so that you can ensure that you submitted the correct file.