0
votes

Im trying to make my variable integer input to be only == to an integer, and if its not I want to print and error message. I have put this in a if statement. I always get an error when I input a string instead of my error message.

age = int(input("Enter age:"))

if age != int:
print("Not a number")
2
here is a discussion about how to test if a string represents an integer in python or not: stackoverflow.com/questions/3501382/… - hiro protagonist
this is for python 3, right? - hiro protagonist

2 Answers

2
votes

you have to use raw_input instead of input

if you want this to repeat until you have the correct value you can do this

while True:
    try:
        age = int(raw_input("Enter age:"))
    except ValueError:
        print("Not a number")

    if age == desired_age: # note I changed the name of your variable to desired_age instead of int
        break

I dont recommend you use variable names like int... its generally a bad practice

2
votes

from the discussion i posted the link above:

age = input("Enter age:")  # raw_input("Enter age:") in python 2

try:
    age = int(age)
except ValueError:
    print('not a number!')

the idea is to try to cast age to an integer.

your attempt of age != int will always fail; age is a string (or an int if you were successful in casting it) and int is a class.