简体   繁体   English

仅使变量整数输入== Python中的整数

[英]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. 我已将其放在if语句中。 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 您必须使用raw_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 我不建议您使用像int这样的变量名。

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. 这个想法是尝试将age转换为整数。

your attempt of age != int will always fail; 您的age != int尝试age != int总是会失败; age is a string (or an int if you were successful in casting it) and int is a class. age是一个字符串(如果成功转换,则为int ),而int是一个类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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