为啥当我输入整数时它显示为不是整数? (Python)[重复]
Posted
技术标签:
【中文标题】为啥当我输入整数时它显示为不是整数? (Python)[重复]【英文标题】:Why does this show as not an integer when I input an integer? (Python) [duplicate]为什么当我输入整数时它显示为不是整数? (Python)[重复] 【发布时间】:2018-05-07 19:27:10 【问题描述】:如您所知,我是一个相当新手的 Python 编码器。截至目前,我只是在制作一些小测试程序,并试图确保我的所有缩进以及在尝试任何大型程序之前都正确完成。 所以我试图确保如果输入不是整数,那么程序会输出一条消息,说明必须输入整数。但是,对于我拥有的当前代码(我认为应该是正确的),无论答案如何,都会输出“请输入整数”消息。我做错了什么?代码如下:
a = input("What is your age?")
b = 7
c = ((a-2) * 4) +25
if a == int:
print "Your age in a small dog's years is:", ((a-2) * 4)+28
print "Your age in a medium sized dog's years is:", ((a-2) * 6)+27
print "Your age in a big dog's years is:", ((a-2) * 9)+22
print "Your age in cat years is:", c
print "Your age in guinea pig years is:", a * 15
print "Your age in hamster years is:", a * 20
print "Your age in pig years is:", ((a-1) * 4)+18
print "Your age in goldfish years is:", ((a-1) * 8)+188
print "Your age in cow years is:", ((a-1) * 4)+14
print "Your age in horse years is:", a * 3
print "Your age in goat years is:", ((a-1) * 6)+18
print "Your age in rabbit years is:", ((a-1) * 8)+20
print "Your age in chinchilla years is:", ((a-1) * 7)+17
elif a != int:
print "You must enter an integer!"
否则它会起作用,只是这个小结尾的两行似乎毁了它。 谢谢。
【问题讨论】:
a == int
不是您检查变量类型的方式。
***.com/questions/3501382/…
确保您的输入是整数int(input())
。使用您当前的实施检查type(a) and you will see it says string
【参考方案1】:
Python 3:
a = input("What is your age?") # this is a string input
a = int(input("What is your age?")) # you need an integer input
elif(isinstance(a, int)) # this is how you check if a is integer
对于您在 Python 2 中的情况:
a = raw_input("What is your age?") # input is interpreted as unicode here
try:
a = int(a)
b = 7
c = ((a-2) * 4) +25
print "Your age in a small dog's years is:", ((a-2) * 4)+28
except:
print "You must enter an integer!"
【讨论】:
a = input("What is your age?") b = 7 c = ((a-2) * 4) +25 if(isinstance(a, int)): #Stuff else: print "You must input an integer!"
如果我输入的不是数字,它会给我错误?
啊,我明白了,您使用的是 python2。让我更新答案
另外,我建议不要在 python 2 中使用input()
以上是关于为啥当我输入整数时它显示为不是整数? (Python)[重复]的主要内容,如果未能解决你的问题,请参考以下文章
为啥当我输入整数数据时,它的值在 Codeigniter 中总是四舍五入