Python Forum

Full Version: while + if + elif + else combination
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is wrong with this code?? If I input a number it says I get 'That is not a number'. Why?

while True:
    text = input('Number (or \'Quit\' to exit): ')
    if text == 'Quit':
        print('...exiting program')
        break
    elif text.isnumeric == True :
            print(int(text) + 2)
    else:
            print('That is not a number', end = '\n')
Thanks

Haha, I figured it out. It's meant to be is.numeric()
Your elif line has a couple of problems. First of all, you are comparing the method isnumeric itself to true, not the result of isnumeric. You would want to call isnumeric (text.isnumeric()). Second, isnumeric is going to be True for a lot of things that int is not going to be able to handle. The isdigit method works better with in, but only for positive numbers. Negative numbers that int can handle come back False from isdigit. Finally, you should not compare to True, the conditional already checks if it's True. So better would be:

elif text.isdigit():
Even better would be a try/except block:

try:
    print(int(text) * 2)
except ValueError:
    print('That is not a number') # '\n' is the default for end, you don't need to add it explicitly.