Why does this show as not an integer when I input an integer? (Python)
本问题已经有最佳答案,请猛点这里访问。
如你所知,我是一个相当新手的Python编码人员。目前,我只是做了一些小的测试程序,在尝试任何大的程序之前,要确保所有的缩进和任何正确的操作。因此,我试图确保如果输入不是整数,那么程序输出一条消息,表示必须输入整数。但是,对于我所拥有的当前代码(我认为应该是正确的),无论答案是什么,都会输出"请输入一个整数"消息。我做错了什么?代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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!" |
否则它会起作用,只是这条小小的两头线,似乎会毁了它。谢谢。
Python 3:
1 2 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中的情况:
1 2 3 4 5 6 7 8 9 | 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!" |