Saturday, August 15, 2015

Intro to Programming with Python - Tutorial 9 - Exercise 1

In the 9th tutorial in our introduction to programming using Python series we present the while loops.
The video tutorial can be found here:
https://youtu.be/rW-iqRxP6Cs

Our first exercise for this tutorial is to create a number adder/averager.
When you run your code it should prompt the user to enter numbers until the user says 'Done'
Then it should display the number of numbers the user entered, the total and average for them.

Here is a screen shot of what you should see when you run your program:


The code to accomplish this is as follows:
# First we create variables for the number of numbers and the total
numberOfNumbers = 0
total = 0
# Now we loop until the user says Done
while True:
userInput = input('Please enter a number or "Done" if finished: ')
if userInput == 'Done':
break
num = int(userInput)
# Note total += num is the same as saying total = total + num
total += num
numberOfNumbers += 1
# We have to check if user entered no numbers.
# If we do not check and we divide (total / numberOfNumbers) we would
# be dividing by zero and Python would complain
if numberOfNumbers == 0:
print('You did not enter any numbers')
else:
avg = total / numberOfNumbers
print('You entered %s numbers. Total is %s and average is %s' % (numberOfNumbers, total, avg))

No comments:

Post a Comment