Reputation: 137
Write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. You need to use a break statement to exit the while loop. Here is what I have gotten so far:
number_of_entries = int(input('Please enter the number of numbers: '))
entries = []
count = 0
while count < number_of_entries:
entry = float(input('Entry:'))
entries.append(entry)
count = count + 1
average = sum(entries)/number_of_entries
print(average)
This first prompts the user to enter the number of numbers then it prompts them for the entries the while loop continues prompting for numbers until the count of numbers equals the number of numbers the user inputted. The entries are saved into a list and the sum of the numbers in the list is used to get the average which is stored in the average variable. If the user doesn't input anything (just press enter) it is supposed to just find the average of the numbers that were already inputted rather than result in an error code. I know that I have to use a break statement but I just can't figure it out.
Upvotes: 1
Views: 4247
Reputation: 180522
break if the user just presses enter or then cast and append
while True:
entry = input('Entry:')
if not entry: # catch empty string and break the loop
break
entries.append(float(entry))
average = sum(entries)/len(entries)
If you are only breaking when the user hits enter the number_of_entries
is irrelevant. You can use the length of the list to get the average, if the user entered 10 for number_of_entries
with your original while count < number_of_entries:
and then hit enter after inputting 5 numbers average = sum(entries)/number_of_entries
would be wrong.
Upvotes: 2