首页 > 解决方案 > 在 for 循环中计算输入

问题描述

变量“countT”会在每次输入后不断添加,即使 if 语句说要向“countT”添加 0,它也会继续这样做。我试过这样做,如果 temp <= 0: 那么它也不会向“countT”添加任何内容。

countT = 0
temp = 0
listT = []

breath = input("Do you have shortness of breath (y/n)? ")
cough = input("Do you have a cough(y/n)? ")
sorethroat_runnynose = input("Do you have a sore throat/runny nose (y/n)? ")
nausea = input("Do you have diarrhea, nausea and vomiting (y/n)? ")

if str.lower(breath)== 'y' and str.lower(cough)== 'y'and str.lower(sorethroat_runnynose)== 'n' and str.lower(nausea)== 'n':
    print("Enter 5 most recent temperature readings:")
    for x in range (1,6):
        temp2= int(input("Temp: "))
        temp += temp2
        listT.append(temp2)
        if temp == 0:
            countT +=0
        else:
            countT +=1

    avgT = (temp/countT) 

    print("Your max Temp was: ",(max(listT)))
    print("Average Temp is: ",avgT)
    print("You likely have the influenza virus")

    if avgT > 100 and temp > max(listT):
       print("Please seek medical attention now!") 

    elif avgT > 99:
        print("Monitor your condition closely!")

elif str.lower(breath)== 'n' and str.lower(cough)== 'n' and str.lower(sorethroat_runnynose)== 'n' and str.lower(nausea)== 'n':
    print("There are no symptoms but you should wait to see if you develop any.")

else:
    print("you likely have the influenza virus.")

标签: pythonfor-loopif-statement

解决方案


从你的问题我理解的是,如果当前输入不是 0,你想加 1。countT它现在不能正常工作的原因是你正在检查语句tempif temp == 0:尽管你应该检查temp2,因为temp2是输入并且temp是总和输入。此外,您可以在一个 if 语句(没有 else)中编写整个检查,如下所示:

if temp != 0:
    countT +=1

或者如果您还想消除负面输入:

if temp > 0:
    countT +=1

推荐阅读