Question

Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.

Code:

numbers = []

while True:
    user_input = input("Enter a number: ")
    if user_input == "":
        break
    try:
        number = float(user_input)
    except:
        print('You have inputted a bad number') 
    else:
        numbers.append(number)

for i in numbers:
    print(i, end=" ")


total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))

No correct solution

OTHER TIPS

Your question could be presented better, but from what you've said it looks like you need to modify the while condition.

while len(numbers) < 20:
    user_input = input("Enter a number:" )
    ....

Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.

Each time the user enters input, add 1 to a variable, as such:

numbers = []
entered = 0

while entered < 20:
    user_input = input("Enter a number: ")
    if user_input == "":
        break
    else:
        numbers.append(number)

    try:
        number = float(user_input)
    except:
        print('You have inputted a bad number')
        continue

for i in numbers:
print(i, end=" ")

total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1

Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:

>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10

NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top