python - 为什么即使我尝试过,它也会出现错误?
问题描述
def temperature_def(tem):
try:
if tem >= 34 and tem <= 38:
return tem
else:
print("You can not enter the list!")
quit()
except:
print("Enter a number!")
quit()
pearson1 = People_class((input("Name and Surname (with out accents): ").lower()), int(input("Age: ")),
covid_status_def(input("Someone close to you either has covid or had it? ").lower().strip()),
temperature_def(float(input("What is your temperature in degrees? "))))
在这里,我试图为 if 语句获取一个数字,我在最后一行输入。
try 和 except 应该识别是否输入了一个数字(不知道这是否是一个单词),并且应该按照以下方式进行操作,但是,当我输入不是数字的内容时,它会出现错误。
为了澄清我正在做一个列表并且“float(input(...”)不能移动(据我所知)。
提前致谢,节日快乐:D
解决方案
那是因为您明确尝试将用户输入转换为浮点数:
temperature_def(float(input("What is your temperature in degrees? ")))
您应该float
从上面删除并传递输入而不进行任何显式转换。如果输入不正确,try-except
您的方法中定义的将处理它。
编辑:由于您从 中删除了浮动转换input
,您现在必须将其放在try
块内:
try:
temp = float(temp)
if tem >= 34 and tem <= 38:
return tem
else:
print("You can not enter the list!")
quit()
except:
print("Enter a number!")
quit()
推荐阅读
- angular - Angular CLI 是否会缩小/丑化资产?
- sorbet - 为什么不推断 T::Boolean 的真假?
- javascript - 为什么在角度测试中没有接收到 http 请求
- python - 减少使用 pandas 的基于 pyinstaller 的 Excel 转换器的文件大小
- html - 如何使 div 不大于其内容 - 是因为 display: flex 吗?
- excel - Excel:在多列中查找具有重复项的多个值
- arrays - virsh 获取阵列中所有虚拟机的磁盘位置
- c# - 存储为 Varchar(9) 的 SSN 的 Razor 页面显示模板
- firebase - Firebaseui FirestoreRecyclerAdapter:如何使用 DocumentReference 指向的数据
- android - 如何解决flutter中“XXXXX类型的对象未在GetIt中注册”的问题?