检查输入Python 3.5.2

时间:2016-09-22 16:00:41

标签: python input types

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" )

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

2 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码:

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" )

以下是输出:

>>> ================================ 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

答案 1 :(得分:-1)

input()函数总是返回一个字符串。 首先转换为intfloat