Basic Exceptions

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:
            message = 'Please input a number and a divisor to check, in the format "X Y": '
            num, check = input(message).split()
        except ValueError:
            print('Not an integer, please input two integers')
            return int(num), int(check)

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.