How to use the number 0 as a stop/break?

Viewed 574

The code needs to ask user to enter any numbers by choice and as many numbers as he/she wants and put them into a list. (This is not what I ask reader to focus on, just an introduction about how the code works!)

When user enters the number 0, the program needs to print the sum, average, minimum and maximum of the list, without including the zero itself.

If possible, I do not want to use any Python import libraries.

try:
    user_list = []

    print("PRESS 0 to see: \n\t 1. Sum \n\t 2. Average \n\t 3. Minimum \n\t 4. Maximum")

    while True:
        print("Type number by choice and hit Enter: ")
        user_list.append(int(input()))

except:
    print(user_list)

What I tried was to implement a if statement after the except statement which still gave me the oppurtinity to enter as many numbers as I wanted, but when entered a letter it stopped.

4 Answers

Possibly variant, if you want to use exceptions:

class ProcessList(BaseException):
    pass

try:
    user_list = []

    print("PRESS 0 to see: \n\t 1. Sum \n\t 2. Average \n\t 3. Minimum \n\t 4. Maximum")

    while True:
        value = int(input("Type number by choice and hit Enter: "))
        if 0 == value:
            raise ProcessList()
        user_list.append(value)

except ProcessList:
    s = sum(user_list)
    print(f'avg = {0 if not user_list else s / len(user_list)}, sum = {s}, min = {min(user_list)}, max = {max(user_list)}')


user_list = []

print("PRESS 0 to see: \n\t 1. Sum \n\t 2. Average \n\t 3. Minimum \n\t 4. Maximum")

while True:
    value = int(input('Type number by choice and hit Enter: '))
    if value != 0:
        user_list.append(value)
    else: break
sum_of = sum(user_list)
max_of = max(user_list)
min_of = min(user_list)
avg_of = sum_of / len(user_list)

print(sum_of)
print(max_of)
print(min_of)
print(avg_of)

You can append all non-zero values to list, and exit from a loop if user enter a zero value:

while True:
    x = int(input("Type number by choice and hit Enter: "))
    if x != 0:
        user_list.append(x)
    else:
        break

If you use try..except block only to handle incorrect input, you can move it to the loop, and execution will not be interrupted when incorrect value was entered.

while True:
    try:
        x = int(input("Type number by choice and hit Enter: "))
        if x != 0:
            user_list.append(x)
        else:
            break
    except:
        print("Please enter a number.")

You can also set a prompt text as input() function argument.

Give something like this a go:

def main():
    values = []
    while True:
        value = int(input('Enter numbers to add them to a list, enter 0 to get summary statistics'))
        if value == 0:
            break
        values.append(value)


    print('Sum: ', sum(values))
    print('Average :', sum(values)/ len(values))
    print('Min : ', min(values))
    print('Max: ', max(values))


main()

Here I make this into a function so that it might be re-usable. I then create a list for the values to be added to -> I then want to loop until the correct condition -> I then ask for the input with some validation i.e. requiring the input to be an Integer (can change that to float if needed) -> Then deal with the exceptions! If 0 then break the loop (good practice to deal with exceptions first) -> append the values to the list if they have made it through the validation step.

Related