2

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 5

1

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

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

2 Comments

Thankyou heaps, good job on avoiding the error on division by zero if no elements in the list, very handy.
@Hard_Whey If the user provides a blank line on the very first attempt then the list will not have any element and no operation should be done, check the updated posted solution.
1

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.")

Comments

1

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)))

2 Comments

Great explanation and very well explained, thankyou for your time. I understand input() a lot better now after this, I had no idea I could do what you did on line 3, thanks again.
My pleasure. If this was, or another answer was the correct answer you were looking for, kindly mark it as answered. Thanks!
1

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.

Comments

0

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

3 Comments

Using the type() method isn't flawless, since it is possible that the user inputs a float type, such as 5.0. This would therefore consider 5.0 as a float, and not pass the condition.
I guess the only way is by int-ing and try except? Because calling a method like round() won't work on non-numeric input...
Yes, I would personally do try-except, however there may be other "better" methods which I may not be aware of.

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.