string - 根据值检查输入时出错
问题描述
我对 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")
解决方案
此语句创建一个名为的字符串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%)的分数在某种程度上是无法获得的。但我对这个假设不做任何价值判断,我假设你知道你在用价值检查做什么:-)
推荐阅读
- android - 确保 gradle 依赖项在 app bundle 中包含 32 位和 64 位库
- c++ - 排队或不排队以获得低延迟
- kotlin - 如果在 flatMap { ... } 映射器函数中进行阻塞操作是安全的?
- c++ - 如何使用 Rcpp 就地缩放 NumericMatrix?
- xamarin - Xamarin:Xamarin Google Map 始终显示 Xamarin.Forms.GoogleMaps 而不是加载地图
- linux - 如何了解 GNU 并行一次可以运行的最大进程数?
- web-crawler - 如何使用 nightmare.js 拒绝自动访问此页面
- websocket - 如何使用 Adonis 的 websocket 中间件返回 401 错误
- dynamics-crm - 在 Microsoft Dynamics CRM 实体中显示特定字段更改的查询
- hadoop - hdfs如何计算已用(剩余)空间配额?如何将小文件存储在hdfs中?