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!