PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

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

 May 12, 2022     append, list, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing