One common use of a while loop is to keep asking for input until the user puts in something sensible. If we are asking for the length of something and the user types in number -5, or 'dog', or #, or just accidentally presses the enter key without a number, then we should print a message saying that input was no good and to ask them to try again.
We can sort out the first of these bad input examples using if answer > 0: but the other examples will cause the program to crash because they produce an error - the program can't turn those inputs into a number - and this is where try/except comes in.
We only use this around a piece of code could produce an error that will cause a crash .
We ask the program to try to do something and if it works then all is good, the program can continue, but if it goes horribly wrong the except code gives the program something to do instead of crashing.
Suppose we need the user to type in an integer such as how many apples they want to buy, eg
num_apples = int(input("How many apples do you want? "))
If the user types in anything other than an integer - 2.435, dog, #, etc - then the program will crash because the int can't make an integer out of those things.
So we can get the input then TRY to change it to an integer like this
num_apples = input("How many apples do you want? ")
try:
num_apples = int(num_apples)
If the user has typed in an integer then this will all work fine, num_apples will now be a number and so can be used in calculations later in the program. However, if an error occurs when it tries to turn num_apples into an integer we can provide the program with a bit of code to run.
num_apples = input("How many apples do you want? ")
try:
num_apples = int(num_apples)
except:
print("That is not a valid input, please try again.")
The code in the except block only gets run if there is an error in the try block, otherwise it is ignored and skipped over.
The program will now not crash when the input is not an integer but num_apples is not a number now so any calculations will cause problems.
If we set up a loop with a sentinel variable that gets changed inside the try block then the loop will keep going round and round asking the same question until the user types in a valid answer, like this
invalid = True
while invalid:
num_apples = input("How many apples do you want? ")
try:
num_apples = int(num_apples)
invalid = False
except:
print("That is not a valid input, please try again.")
print("Thank you")
Invalid is a Boolean variable which makes reading the code much easier. We enter the loop, ask how many apples - which gets recorded as text, then one of two things happen:
if the user enters an integer the try block works - turning num_apples into an integer, invalid gets set to False, the except block is skipped, the program goes back up to the while loop, finds that the condition is not true any more so skips out of the loop to the next line where it prints "Thank you".
if the user doesn't enter an integer the try block raises an error when it tries to turn the text into an integer which causes the except block to run straight away - crucially before invalid gets changes to False - this prints the error message then the while loop runs again because invalid is still True. The question gets asked again, the user types in a new answer and we see if it is an integer or not all over again.
In this way we are sure that we only leave this question and move on with our program once we have a valid answer.
Now that we are sure the answer is an integer we can check that it is a sensible integer. We could check that it is a positive number and maybe set an upper limit too
invalid = True
while invalid:
num_apples = input("How many apples do you want? ")
try:
num_apples = int(num_apples)
if num_apples > 0 and num_apples < 20:
invalid = False
elif num_apples < 0:
print("Number must be positive")
else:
sure = input("Are you sure you want that many apples? ")
if sure == "y":
print("OK. You're the boss")
invalid = False
except:
print("That is not a valid input, please try again.")
print("Thank you")
Try Except - Part 1
Try Except - Part 2