user3165683
user3165683

Reputation: 367

Try, except - not entering if statement

I have code which I am trying to validate, however it won't enter the if statement:

while True:
    try:
        ISBN = int(input("Please enter a 10 digit number: "))
        print("TT")
        if len(ISBN)!= 10:
            print("T")
            print("That was an incorrect input.")
        else:
            # do code
    except:   
        print("RRRRR")
        print("That was an incorrect input.")

Here is the input/output:

Please enter a 10 digit number: 1234567898
TT
RRRRR
That was an incorrect input.
Please enter a 10 digit number: 

Upvotes: 0

Views: 940

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 77013

You are converting ISBN input to int, and then checking its length.

Change that to

ISBN = input("Please enter a 10 digit number: ")

and convert it to integer value later in your else block.

Note that int objects don't have a length, and hence your code directly goes to the except block.


With my suggested changes, your code becomes

while True:
    try:
        ISBN = input("Please enter a 10 digit number: ")
        print(ISBN)
        if len(ISBN)!= 10:
            print("T")
            print("That was an incorrect input.")
        else:
            ISBN = int(ISBN)
            print(ISBN)
            # do code
    except:   
        print("RRRRR")
        print("That was an incorrect input.")

Note however that you are catching the generic error, and it is better to catch specific ValueError instead.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124000

int objects don't have a length:

>>> len(1234567890)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()

Because you are using a Pokemon exception handler (catching them all) you don't get to have a proper error message telling you this either. Remove your try: / except: or at the very least narrow it down to one or two exception types you want to ignore; for int() conversions, catch only ValueError. Do so only for the int() call, not everything else:

while True:
    try:
        ISBN = int(input("Please enter a 10 digit number: "))
    except ValueError:
        print("That was an incorrect input.")
    else:
        # continue with ISBN being a valid integer

If you want to know the number of digits, either take the length of the string version:

if len(str(isbn)) != 10:

or test for boundaries:

if not (10**10 > isbn >= 10**9):

Either works to validate a number of 10 digits:

>>> isbn = 1234567898
>>> len(str(isbn))
10
>>> (10**10 > isbn >= 10**9)
True

Upvotes: 3

Related Questions