1

I want to handle possible ValueErrors resulting from invalid user input but I still get the red errors in the console instead of the program printing 'Invalid entry' as I intended. I'm not sure what's going wrong.

input_number = input("How many numbers would you like the program to calculate the average of?\n>> ")
try:
    input_number = int(input_number)
except ValueError:
    print("Invalid entry")

for i in range(input_number):
    input("Please enter a whole number (%i/%i numbers entered):\n>> " % (i + 1, input_number))

It seems to ignore my try except statement as the error appears on the line of the for statement, saying "TypeError: 'str' object cannot be interpreted as an integer". It still doesn't work even if I amend the except to be "except ValueError or TypeError".

2
  • 2
    except ValueError or TypeError That is not the right syntax for catching multiple errors. Use a comma instead of or. Commented Mar 5, 2022 at 1:46
  • It isn't clear to me what your problem is here. You say that "Invalid entry" is NOT printed at all? ... and yet you then get an error on the for i in range line? That doesn't seem possible given your code. If you're getting both "Invalid entry" and then an error, that makes sense, and the answer provided will help you fix your problem. Commented Mar 5, 2022 at 1:57

2 Answers 2

3

The problem is that when you catch the ValueError, you don't do anything to fix input_number (i.e. make it an int), so the program continues past your try statement and into your range() call, which proceeds to raise another exception because input_number isn't an int.

Simply catching an exception doesn't fix the error that caused it to be raised in the first place. If you catch an exception, you need to understand why it raised, and do something appropriate to correct the situation; blindly catching an exception will often just lead to another error later in your program, as it did here.

One way to correct this situation is to prompt the user again:

while True:
    try:
        input_number = int(input(
            "How many numbers would you like the program to calculate the average of?\n>> "
        ))
        break
    except ValueError:
        print("Invalid entry")

With the above code, the loop continues until input_number is an int.

Since it looks like you'll be wanting to do this again, I'd suggest putting it in a function:

def input_number(prompt: str) -> int:
    """Prompt for a number until a valid int can be returned."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Invalid entry")

n = input_number(
    "How many numbers would you like the program to calculate the average of?\n>> "
)
numbers = [
    input_number(f"Please enter a whole number ({i}/{n} numbers entered):\n>>")
    for i in range(1, n+1)
]
print(f"Average: {sum(numbers)/len(numbers)}")
How many numbers would you like the program to calculate the average of?
>> I don't know
Invalid entry
How many numbers would you like the program to calculate the average of?
>> 4
Please enter a whole number (1/4 numbers entered):
>>5
Please enter a whole number (2/4 numbers entered):
>>42
Please enter a whole number (3/4 numbers entered):
>>???
Invalid entry
Please enter a whole number (3/4 numbers entered):
>>543
Please enter a whole number (4/4 numbers entered):
>>0
Average: 147.5
Sign up to request clarification or add additional context in comments.

Comments

2

The clause should be

except (ValueError, TypeError):
    ...

1 Comment

Note that this doesn't actually fix OP's problem because the TypeError is raised only after the ValueError has been eaten. They'd need to have an entirely separate try/catch block if they wanted to catch the TypeError.

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.