首页 > 解决方案 > 根据值检查输入时出错

问题描述

我对 Python 完全陌生,我正在尝试编写一个小程序。

它包括输入一个介于 0.0 和 1.0 之间的分数。在我编写的代码中,它非常基本,我可以让它出现在终端中,它说enter score:但是,当我输入一个时,我得到了错误message:'>=' not supported between instances of 'str' and 'float'

现在我知道我需要做点什么来修复它,但我的大脑冻结了。有任何想法吗?

score = input("Enter score: ")

if score >= 0.9:
    print('Error, try again!')

if score >= 0.85:
    print('Well Done!!')

if score >= 0.7:
    print('Error, try again')

if score >= 0.6:
    print('Error, try again')

if score <= 0.6:
    print("Error, invalid answer")

标签: stringfloating-point

解决方案


此语句创建一个名为的字符串score,而不是一个数值(例如 a float):

score = input("Enter score: ")

如果你想要一个数值,你需要类似的东西:

score = float(input("Enter score: "))

尽管您可能希望将其包装在异常处理程序中,以防它们输入错误数据:

score = None
while score is None:
    try:
        score = float(input("Enter score: "))
    except ValueError:
        print("*** That was NOT a valid score, try again.")
        score = None # possibly not needed but just to be safe
now_do_something_with(score)

此外,如果您只想打印其中一个字符串,则需要稍作调整,例如:

if score >= 0.9:
    print('Error, try again!')
elif score >= 0.85:
    print('Well Done!!')
elif score >= 0.7:
    print('Error, try again')
elif score >= 0.6:
    print('Error, try again')
else # score <= 0.6:
    print("Error, invalid answer")

顺便说一句,我不确定为什么您认为 90% 或以上(低于 85%)的分数在某种程度上是无法获得的。但我对这个假设不做任何价值判断,我假设你知道你在用价值检查做什么:-)


推荐阅读