Why is != not working to check for an integer in Python

Viewed 85

I am trying to write a simple program that checks if a user inputs an integer, but there is a problem with my code.

I would like to print out the if statement only if input is not an integer. What is wrong with the code? Thanks

a = input('What is your name?: ').capitalize()
b = int(input('How old are you?: '))
if b != int:
    print('Please input a number')
c = 100-b

print(f"{a} is {b} years old and will turn 100 years old in {c} years.")
2 Answers

You're asking python to tell you if a value is equal to a type int.

Note: int() is also a function that converts its argument to an integer value

If you want to check if b is an int (which is pointless anyway because you've already cast the only place it can be populated to an int) then you use isinstance()

if type(b) != int:
    print('Please input a number')

if isinstance(b, int):
    print(f"{a} is {b} years old and will turn 100 years old in {c} years.")

The line int(input()) will output an error if input is not a number, so we are not able to verify even if we use if type(b) != int. It should be like this using try-except to test the input:

a = input('What is your name?: ').capitalize()
b = ''

while type(b) == str:
    b = input('How old are you?: ')
    try:
        b = int(b)
        print(f"{a} is {b} years old and will turn 100 years old in {100-b} years.")
        #break    #while-loop will break when type(b) != str
    except ValueError:
        print('Please input a number')

Output

What is your name?:  perp
How old are you?:  twenty
Please input a number
How old are you?:  20
Perp is 20 years old and will turn 100 years old in 80 years.
Related