检查输入Python 3.5.2

检查输入Python 3.5.2,python,input,types,Python,Input,Types,我需要确保用户只插入INT或float。 当我执行这段代码时,即使我插入INT或float,它也会自动进入while循环。 此代码有什么问题,应该如何处理?input()函数始终返回字符串。 首先转换为int或float。能否尝试使用以下代码: Fahr = input("Insert temperature in Fahrenheit: " ) while type(Fahr) != float or type(Fahr) != int: Fahr = input("Error:

我需要确保用户只插入INT或float。 当我执行这段代码时,即使我插入INT或float,它也会自动进入while循环。 此代码有什么问题,应该如何处理?

input()
函数始终返回字符串。
首先转换为
int
float

能否尝试使用以下代码:

Fahr = input("Insert temperature in Fahrenheit: " ) 

while type(Fahr) != float or type(Fahr) != int:

    Fahr = input("Error: Insert temperature in Fahrenheit: " )

Celcius = ((Fahr) - 32) * 5/9


print("Your imput: " + Fahr + " Fahrenheit" ) 

print("This is equal to: " + Celcius + " Celcius" )
以下是输出:

def inp():
    try:
        Fahr = float(raw_input("Insert temperature in Fahrenheit: " ))
        return Fahr
    except Exception as e:
        return e

Fahr = inp()
while True:
    if 'could not convert' in str(Fahr):
        Fahr = inp()
    else:
        break

Celcius = ((Fahr) - 32) * 5/float(9)

print("Your input: " + str(Fahr) + " Fahrenheit" ) 
print("This is equal to: " + str(Celcius) + " Celcius" )

Fahr
将始终是一个字符串(
str
),这就是
input()
返回的内容。阅读此:或此:我认为解决方案是使用
运算符,而不是
运算符。数字不能同时是整数和浮点。这是Python 2还是Python 3
input()
在这两者之间有不同的功能,我假设Python3.Fahr=int(输入(“插入华氏温度:”)。我现在这样做了,但当我键入一个字符串时,它给我的结果是:以10为底的int()的文本无效:“df”这是正常的。您可以捕获此异常并重试输入。在这种情况下,此答案不包括任何内容,以确保用户输入OP所需的数字。除非用户不输入数字,否则它“将正常工作”,OP说他们“需要确保用户只插入INT或float。”如果用户插入字符串,我必须打印一个错误并让用户插入一个新值。对不起,我是这个网站的新手,这是我的第一个问题。谢谢你的帮助!我已经编辑了代码。请查查。嘿,杰里尔,我试过这个。是的,它可以工作,但只能工作一次。如果我在一个字符串中插入2次。程序崩溃了!我输入了一个修改过的代码,你能检查一下吗?
>>> ================================ RESTART ================================
>>> 
Insert temperature in Fahrenheit: hello
Insert temperature in Fahrenheit: !@
Insert temperature in Fahrenheit: ()()((
Insert temperature in Fahrenheit: 10.5
Your input: 10.5 Fahrenheit
This is equal to: -11.9444444444 Celcius