This code uses a while
loop and a try-except
block to get a valid integer input from the user.
The while
loop will continue to run indefinitely until the user provides a valid integer input.
Inside the while
loop, the code uses a try-except
block to try to convert the user’s input to an integer using the int()
function. If the user’s input is not a valid integer, a ValueError
will be raised.
In case a ValueError
is raised, the code inside the except
block will be executed. The code inside the except
block first prints the message “invalid number, please try again” and then prints the error message contained in the exception object e
using print(e)
.
The loop will continue to run until a valid integer is entered by the user. Once a valid integer is entered, the break
statement will be executed and the loop will exit.
Finally, the code outside the loop prints the message “go on”.
The try-except
block allows the code to continue executing even in the presence of errors, without crashing the program. It provides a way to handle exceptions and provides a more user-friendly output, in this case, prompting the user to try again until a valid integer is entered.
while True:
try:
userInput = int(input("Please enter a number: "))
break
except ValueError as e:
print("invalid number, please try again", e)
print("go on")
Please enter a number: g
invalid number, please try again invalid literal for int() with base 10: 'g'
Please enter a number: 5.6
invalid number, please try again invalid literal for int() with base 10: '5.6'
Please enter a number: 5
go on