Thursday, May 12, 2022

[FIXED] How to append a list in Python based on condition?

Issue

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


Solution

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.



Answered By - Pablo Santa Cruz
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.