No BS: using a ‘while True’ loop and a ‘continue’ line in an exception is good because it gives the user another go at an input (if that’s what it was used for) without having to go through the whole program again.
With BS: So I just put together a quick program to check if one integer is divisible by another. In doing so, I had to use an exception block to make sure the user wasn’t putting in any funky inputs except from integers. By making use of a
def inputinteger(): while True: try: message = 'Please input a number and a divisor to check, in the format "X Y": ' num, check = input(message).split() int(num);int(check) except ValueError: print('Not an integer, please input two integers') continue else: return int(num), int(check) break
We can break this down into the following chunks:
- When asking for input, show the message first.
- Define num and check as the two user inputs
- Then convert those into integers
- If Python throws a ValueError, print out a message and continue trying.
- If not (hence assuming we got two integers) return int(num) and int(check) back to the main program.
This is beneficial because making use of the while loop here allows us to add the command continue. So if we do get a ValueError, we don’t have to start the program all over again.