仅使变量整数输入== Python中的整数 [英] Making a variable integer input only == an integer in Python
本文介绍了仅使变量整数输入== Python中的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使我的变量整数输入仅==成为整数,如果不是,我想打印并显示错误消息.我已将其放在 if 语句中.当我输入字符串而不是错误消息时,总是会出现错误.
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")
推荐答案
您必须使用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
我不建议您使用像int这样的变量名...这通常是一个坏习惯
I dont recommend you use variable names like int... its generally a bad practice
这篇关于仅使变量整数输入== Python中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文