1

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.

1
  • 5
    Can you please use a title that actually reflects the problem, not your motivation to asks the question? Your question title does not set it apart from all the other questions by new Python users. Commented Aug 5, 2015 at 11:51

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried it and I just keep getting: invalid literal for int() with base 10: '1.5' from MyPyTutor. I don't know what that means.
It means you are not using my code, where am I using int?
Ohhh oops silly me. i forgot to switch one of the int() to float() so I couldn't use inputs like 1.5. It worked :D Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.