I am having trouble in appending a list. Following is the code:
score_Resp = 0
score_O2Sat = 5
score_SBP = 0
score_HR = 1
score_Temp = 0
Abnormal = []
if score_Resp != 0:
Abnormal.append("Resp")
elif score_O2Sat != 0:
Abnormal.append("O2Sat")
elif score_SBP != 0:
Abnormal.append("SBP")
elif score_HR != 0:
Abnormal.append("HR")
elif score_Temp != 0:
Abnormal.append("Temp")
else:
print("Invalid Statement!")
print("Abnormal Vitals:", Abnormal)
The output:
Abnormal Vitals: ['O2Sat']
when it should be:
Abnormal Vitals: ['O2Sat', 'HR']
Can someone help me what went wrong? And also, can someone refine the code with less code? Thnx
CodePudding user response:
You should not be using elif
. Just plain ifs
to evaluate each and every condition.
Like this:
if score_Resp != 0:
Abnormal.append("Resp")
if score_O2Sat != 0:
Abnormal.append("O2Sat")
if score_SBP != 0:
Abnormal.append("SBP")
if score_HR != 0:
Abnormal.append("HR")
if score_Temp != 0:
Abnormal.append("Temp")
The elif
clause is a else if
. So, when your code evaluates to True
the first one, it just ignores the rest. That's why you are not getting the expected result.
CodePudding user response:
You can try:
score_Resp = 0
score_O2Sat = 5
score_SBP = 0
score_HR = 1
score_Temp = 0
Abnormal = []
if score_Resp != 0:
Abnormal.append("Resp")
if score_O2Sat != 0:
Abnormal.append("O2Sat")
if score_SBP != 0:
Abnormal.append("SBP")
if score_HR != 0:
Abnormal.append("HR")
if score_Temp != 0:
Abnormal.append("Temp")
print("Abnormal Vitals:", Abnormal)
CodePudding user response:
Use only if to go through every condition and check it