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

北慕城南 提交于 2020-01-07 03:01:10

问题


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

回答1:


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:


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.



来源:https://stackoverflow.com/questions/32998546/making-a-variable-integer-input-only-an-integer-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!