检查输入是int还是float



我想要一个while循环将输入存储在一个变量中,并在打印语句和打破循环之前检查它是整数还是浮点数。如果变量没有通过检查,我希望它继续回到循环的顶部,并再次请求输入,直到得到有效的响应。

不管输入是什么,循环都会再次请求输入,并且似乎会跳过if条件块。

def FeelingCalc():
Monday = 0
while Monday == 0:
Monday = input("On a scale of 1 to 10, how did you feel on Monday? ")
if isinstance(Monday,(int,float)) and 11 > float(Monday) > 0:
print("Alright. Let's move on.")
break
else:
print("Please type a whole number between 1 and 10.")
Monday = 0
continue

我为if条件尝试了不同的解决方案,如:

if Monday != type(int)

但这似乎也没有任何作用。它仍然会转到else块

问题就在这里:

if isinstance(Monday,(int,float)) and 11 > float(Monday) > 0:

因为Monday是由input()派生的,所以它总是一个字符串。如果不是字符串,而是整型或浮点型,则不需要将其强制转换为浮点型。您可能需要这样的内容:

try:
x = float(input())
except:
print("Please enter a number ")
if x > 11 or x < 0:
print("Number must be in range 1-10")

编辑如果你不想要int以外的任何东西(就像其他答案假设的那样),用int代替float

当你使用input时,你总是得到字符串。因此,您必须将Monday转换为整数或浮点数。

Monday = int(input("On a scale of 1 to 10, how did you feel on Monday? "))

编辑

你可能想使用tryblock:

try:
Monday = float(input("On a scale of 1 to 10, how did you feel on Monday?"))
except: 
Monday = 0

最新更新