【问题标题】:Check on input Python 3.5.2 [duplicate]检查输入 Python 3.5.2 [重复]
【发布时间】:2017-01-31 07:28:16
【问题描述】:
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 循环。 这段代码有什么问题,应该怎么办?

【问题讨论】:

  • Fahr 将始终是一个字符串 (str),这就是 input() 返回的内容。
  • 我相信解决方案是使用and 运算符而不是or 运算符。一个数字不能同时是整数和浮点数。
  • 这是 Python 2 还是 Python 3? input() 两者之间有不同的功能,我假设是 python 3。

标签: python input types


【解决方案1】:

你可以试试下面的代码:

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

【讨论】:

  • 除非用户不输入数字,否则它“会正常工作”,并且 OP 说他们“需要确保用户只插入 INT 或浮点数”,这不是检查。
  • 如果他插入一个字符串,我必须打印一个错误并让用户插入一个新值。对不起,我是这个网站的新手,这是我的第一个问题。感谢您的帮助!
  • 我已经编辑了代码。请检查。
  • 嘿 Jeril,我试过了。是的,它有效,但只有 1 次。因此,如果我插入 2 次字符串。程序崩溃了!
  • 我放了一个修改过的代码,你能检查一下吗?
【解决方案2】:

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

【讨论】:

  • Fahr = int(input("插入华氏温度:" )) .我现在这样做了,但是当我输入一个字符串时,它给了我: int() 以 10 为底的无效文字:'df'
  • 这很正常。您可以捕获此异常并在这种情况下重试输入
  • 此答案不包括任何确保用户输入数字的内容,这是 OP 要求的。
猜你喜欢
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 2014-11-05
  • 2011-11-19
  • 2016-11-19
  • 2018-05-08
  • 2021-10-01
  • 1970-01-01
相关资源
最近更新 更多