为什么即使我尝试了一下,也会出现错误?

2024-05-05 13:16:58 发布

您现在位置: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 and except应该识别是否输入了数字(不知道这是否是一个单词),并且应该按照下面的操作,但是,当我输入的不是数字的内容时,它会出现错误

为了澄清,我正在做一个列表,“float(input(…)”不能移动(据我所知)

提前感谢,节日快乐:D


Tags: andinputreturnifdef数字floatlower
1条回答
网友
1楼 · 发布于 2024-05-05 13:16:58

这是因为您正显式地尝试将用户输入转换为浮点:

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

相关问题 更多 >