首页 > 解决方案 > 为什么即使我尝试过,它也会出现错误?

问题描述

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

标签: pythonif-statementtry-catch

解决方案


那是因为您明确尝试将用户输入转换为浮点数:

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

推荐阅读