While loop integer input

Viewed 261

I have an activity for some practice for a Python class. The aim is to have unlimited amount of input from the user and assuming user is inputting correct data. The input needs to end when a blank line is detected. (this is what seems to have me stumped, trying to avoid a Value Error when doing this.) After input ends I need to sort numbers and find the total of numbers and average of numbers.

numbers = []
num_input = []
tot_numbers = []

while num_input != "":
    try:
        num_input = int((input("Input a number: ")))
        numbers.append(num_input)
        numbers.sort()
        print(numbers)

    except:

        pass
        print("Sorted numbers: ", numbers)
        tot_numbers = sum(numbers)
        print("Total of numbers: ", tot_numbers)
        avg_numbers = tot_numbers / len(numbers)
        print("Average of numbers: ", avg_numbers)
        print("Finished.")
        break

This code above is what I have come to and it works but I am not too happy with it because of using 'except'. I know there is a better way and that it probably uses an if statement within the while loop, I have been playing around with something like:

if num_input.isnumeric():

but I get an AttributeError because I can't check if a list is numeric, any help would be greatly appreciated, thankyou!

5 Answers

Check that the input is digit then only cast it to int and store it into the list and perform operation as below:

numbers = []
num_input = []
tot_numbers = []
while num_input != "":
    num_input = input("Input a number: ")
    # Check if it input is digit then only append it to the list after casting it to int
    if num_input.isdigit():
        numbers.append(int(num_input))
        numbers.sort()
        print(numbers)
    else:
        # if user at first attemp entres blank line then there will not be any elements in the list
        # so only if list has some elements then only these operations should be doen
        if len(numbers)>0:
            print("Sorted numbers: ", numbers)
            tot_numbers = sum(numbers)
            print("Total of numbers: ", tot_numbers)
            avg_numbers = tot_numbers / len(numbers)
            print("Average of numbers: ", avg_numbers)
            print("Finished.")
        break

Check this out:

numbers = []
num_input = []
tot_numbers = []
num_input = input("Input a number: ")
while num_input != "":
    numbers.append(int(num_input))
    numbers.sort()
    print(numbers)
    num_input = input("Input a number: ")

print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")

We can achieve your desired solution without the try except, as you said. I have revised some of your code and added an explanation to the changes in the comments.

numbers = []
#  first user input prompt
num_input = input("Input a number: ")

# isnumeric() checks if strings contain only numbers, and will return True if so, False if not
while num_input.isnumeric():
    # append to the 'numbers' list, converting it into an int (since we're sure that it's an int now)
    numbers.append(int(num_input))
    # prompt the user again
    num_input = input("Input a number: ")
# we can sort the list after all the elements are added, so it's called just once
numbers.sort()
tot_numbers = sum(numbers)
print("Sorted numbers: ", numbers)
print("Total of numbers: ", tot_numbers)
print("Average of numbers: ", (tot_numbers / len(numbers)))

I'll throw my hat in the ring. ;^) The key, I think, is accepting that the user input will either be a valid number or nothing at all. If nothing, then you are done looping. If a valid number then convert it to an int and add it to a list until looping is done. Once done, if any numbers at all perform your operations and print your results.

Edit: Fixed the bug Hetal caught.

Example:

numbers = []
while True:
    num_text = input("Input a number: ")
    if not num_text:
        break
    numbers.append(int(num_text))

if numbers:
    print(f"Sorted numbers: {sorted(numbers)}")

    tot_numbers = sum(numbers)
    print(f"Sum of numbers: {tot_numbers}")

    avg_numbers = tot_numbers / len(numbers)
    print(f"Avg of numbers: {avg_numbers:.2f}")

print("Finished.")

Output:

Input a number:  2
Input a number:  3
Input a number:  1
Input a number:  
Sorted numbers: [1, 2, 3]
Sum of numbers: 6
Avg of numbers: 2.00
Finished.

There is a few things wrong with your code, first num_input is not an array, you put a singular value into it with the input() line. Next, you don't need a pass after except if there are lines of code after it.

Here is what you want to accomplish with the type() function:

num_input = input("Here: ")
if type(num_input) == int:
    num_input = int(num_input)
    #code
else:
    #Its not an integer

The reason why you get the error is because that method doesn't exist, type() is the one you are looking for

Related