A common use of loops is to add several numbers together, or count how many times something is entered. This requires setting a total or a counter to zero, and then keep adding to the it inside the loop.
Suppose you are head teacher of Beanotown High. The number of pupils in each year S1 to S6 is as follows:
110,133,97,127,86,48. You have written a program (below) to input each of these numbers and add them up.
Run the program, enter the numbers above.
In [ ]:
total = 0 # initialise total
for yeargroup in range(6):
prompt = "How many pupils are in year S"+str(yeargroup+1)+": "
pupils = int(input(prompt))
total = total + pupils # add to total
print("Total = ", total)
If you have done it right, you should see
Total = 601
In [ ]:
vauxhall = 0
ford = 0
mazda = 0
for car in range(10):
car_make = input("Enter make of car f, v or m: ")
if car_make == "f":
ford = ford + 1 # it's a ford!
if car_make == "v":
vauxhall = vauxhall + 1 # another vauxhall
if car_make == "m":
mazda += 1 # += 1 is a nice shorthand for adding 1
print("\nYou saw:") # \n forces a new line.
print(str(ford)+" Fords,")
print(str(vauxhall)+" Vauxhalls,")
print(str(mazda)+" Mazdas.")
input("Press Enter to Finish")
Run the program above, if you haven't already! It just runs for 10 cars.
Now, change the copy of the program below to add another make of car, eg. Kia, Skoda, Jaguar. Try out your program to see that it works
In [ ]:
# Edit this copy of the program to handle another make of car.
vauxhall = 0
ford = 0
mazda = 0
for car in range(10):
car_make = input("Enter make of car f, v or m: ")
if car_make == "f":
ford = ford + 1 # it's a ford!
if car_make == "v":
vauxhall = vauxhall + 1 # anothber vauxhall
if car_make == "m":
mazda += 1 # += 1 is a nice shorthand for adding 1
print("\nYou saw:") # \n forces a new line.
print(str(ford)+" Fords,")
print(str(vauxhall)+" Vauxhalls,")
print(str(mazda)+" Mazdas.")
input("Press Enter to Finish")
You can now complete task 24, 27, 28.