简体   繁体   中英

Making a variable integer input only == an integer in Python

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM