2

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.")
blackraven
  • 5,284
  • 7
  • 19
  • 45
pc510895
  • 69
  • 1
  • 7
  • 1
    You're comparing a number to a function. Of course they are different! – Sören Aug 20 '22 at 06:51
  • Your test *b != int* makes no sense. If the input is not a valid base 10 integer then you'll get a ValueError exception. If you want to know if a variable refers to a particular type then use *isinstance* – DarkKnight Aug 20 '22 at 06:52
  • Hint: `int` is a **function** that converts its argument to an integer value. – Stephen C Aug 20 '22 at 07:06

2 Answers2

1

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.")

blackraven
  • 5,284
  • 7
  • 19
  • 45
Trent
  • 2,909
  • 1
  • 31
  • 46
1

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.
blackraven
  • 5,284
  • 7
  • 19
  • 45
  • It's a pointless test. *isinstance(b, int)* in this code will always be True. If it wasn't an int then an exception (ValueError) would have been raised and the test would never be executed – DarkKnight Aug 20 '22 at 06:55
  • @Stuart I've made an edit to my code.. does this work? – blackraven Aug 20 '22 at 07:03
  • 1
    *except ValueError:* is better (more explicit). Also, you don't give the user an opportunity to re-input a value - the program will just end – DarkKnight Aug 20 '22 at 07:05