pythonerror-checking

How to conventionally check for ValueError in python?


I've used a while True: loop alongside try and except statements to error check a program I've handed in for my university assignment. Upon receiving my grade, I've been marked down for using a True loop, as they are apparently 'forbidden' and inefficient in Python programming.

All programming in Python I've done prior to university, I've used the code style below for catching errors which would crash my program. In the specific code I got marked down for, I was trying to ensure that the user input was an integer, not a float nor string. Here is the snippet of code.

question = input('How old are you? ')
while True: 
    try: 
        question = int(question)
        break
    except ValueError:
        question = input('Please enter an integer: ')

It is noteworthy that I specifically got marked down because I used this method incorporating while True to check for an integer input.

This makes me wonder; what is the proper way to do so? My marker's feedback made me think that what I've done is some primitive method of error checking, but I've never come across anything more advance.

If anyone knows 'the proper and correct way' to ensure that an input is an integer, while forgoing the use of while True, I'd greatly appreciate it!


Solution

  • In this specific case, you can forgo try-except:

    question = input('Please enter an integer.')
    while not question.isdigit():
        question = input(f'{question} is not an integer. Please enter an integer.')
    
    question = int(question)
    

    That said, I would say that there is nothing wrong with your code, and it is in fact idiomatic for this situation, compared to this solution.

    Also, it does differ from your solution in that this checks for user input that can be fully converted to an integer, whereas yours accepts, for example, floats.