In this lab, you are going to practice working with loops, and then you'll explore how loops often work nicely for processing lists.
First, we're going to practice addings some code to an existing while loop.
Exercise 1: Consider the guess-my-number code we looked at in the lecture. When the user guesses wrong, add some code that will tell them whether they were too high or too low. (Hint: add a new conditional statement (or change the exiting one) in the indented part of the code). To make this a little more fun, instead of just hard-coding the secret number as 7, we'll generate a random number between 1 and 100.
import random
secret_number = random.randint(1,100) #this will generate a random integer between 1 and 100
guess = 0
guess_counter = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
guess_counter += 1 #this is the same as guess_counter = guess_counter + 1
if guess == secret_number:
print("That was right, good guess!")
else:
print("Wrong!")
print("That took",guess_counter,"guesses")
The output might look like this:
Exercise 2: Consider the following loops. Before running them, try to predict how many of the iterations will run, and then run them to see if you were right.
x = 0
while x <= 5:
print(x)
x += 1
x = 10
while x > 0:
print(x)
x -= 1
x = 0
while x < 16:
print(x)
x += 2
x = 1
while x < 0:
print(x)
x += 1
Exercise 3: Write a program that asks the user how many times they would like to be greeted, and then use a loop to say "Hello" that many times.
Consider the following code from the lecture where we used a count-controlled loop to run through all the indices of a list.
rainfall = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
counter = 0
while counter < len(rainfall):
print("Day",counter,"had",rainfall[counter],"inches of rainfall.")
counter += 1
Exercise 4: Write a new version of the above code that will only print out rainfall on days where the rainfall amount was > 0.
Exercise 5: Recall the following program which used an accumulator variable total_bill to keep a running total. Write something similar that will find a running total of all the values in the rainfall list (instead of asking the user for input values). You will probably want to set up your loop like the example above, but include an accumulator variable like the example below.
total_bill = 0.0 #accumulator
item_cost = -1
while item_cost != 0.0:
item_cost = float(input("Enter item cost (0 to quit): "))
total_bill += item_cost #this is the same as total_bill = total_bill + item_cost
print("The total is",total_bill)
Note: We could get the same result without a loop by using the sum() function, but it's good to practice it without sum() so you'll be ready for variations of the problem that sum() doesn't work for.
Exercise 6: Something related to finding a sum is finding an average. In that case, you need to divide the sum by the total number of items. A common mistake programmers make when doing this is to write code that looks something like this:
#WARNING: The code below has a logic error - don't use this as a reference
num_values = int(input("How many values do you want to enter? "))
counter = 1
average = 0
while counter <= num_values:
new_val = float(input("input value"+str(counter)+": "))
average += new_val/counter #dividing by total number because that's what you do with an average!
counter += 1
print("The average is",average)
Exericse 7: Here's some code that will create a new empty list, ask the user to enter a new value, and then append the new value to the list.
rainfall = []
new_rainfall_amount = float(input("Enter a new rainfall amount in inches: "))
rainfall.append(new_rainfall_amount)
print("Here are the rainfall amounts you entered:",rainfall)
Add a loop to this code so that it will continue filling up the list with values entered by the user until the user enters a pre-determined "quit" value like -1. Then, print out the resulting list. The output could look something like this:
Challenge Exercise 8: To convert a measurement from inches to centimeters, you multiply it by 2.54. Write a new version of the above exercise that also prints out a list of equivalent measurements in centimeters. The output should look like this:
When you are finished, submit your solution to the Lab 8: Rainfall list assignment on codePost. It will be autograded, and it'll be looking for the output to match the examples above.