0

I'm a new python learner who is trying to figure out how to populate multiple results based on if then conditions in python. I'm unsure how to utilize while loop function in order for me to pull multiple results.

For example,

    if high >= (.20):
        print('High level is Red')
    elif med  >= (.20):
        print('Medium level is Red')
    elif low  >= (.20):
        print('Low level is Red')
    elif grand_total  >= (.20):
        print('Grand Total is Red')    
    else:
        print('None')

As you can see, the above statement gives only one out of five options. But I'm trying to pull out ALL OF CORRECT conditions. Can someone please give me an advice? Thank you in advance!!

Also, I can't use for loop function either because they are all separate dataframes. Or is there any other way?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Crystal
  • 23
  • 5
  • one of the answers here https://stackoverflow.com/questions/41032495/multiple-if-statements-in-python#50656735 – jsotola Feb 14 '23 at 20:43

2 Answers2

1

you can combine all condition together with and and check if result is obtain. or instead of elif you can use if condition only. and save result together.

with and

if high >= (.20) and med  >= (.20) and low  >= (.20) and grand_total  >= (.20):
    print('High level is Red')
    print('Medium level is Red')
    print('Low level is Red')
    print('Grand Total is Red')    
else:
    print('None')

without elif condition, only using if

if high >= (.20):
    print('High level is Red')
if med  >= (.20):
    print('Medium level is Red')
if low  >= (.20):
    print('Low level is Red')
if grand_total  >= (.20):
    print('Grand Total is Red')    
if not ( high >= (.20)) and  not (med  >= (.20)) and not (low  >= (.20)) and not (grand_total  >= (.20)):
    print('None')
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1

The most simple solution is to replace the "elif" statements with their own individual "if" statements, then have the last "else" be "if grand_total < 0.2"

i.e.

    if high >= (.20):
        print('High level is Red')
    if med  >= (.20):
        print('Medium level is Red')
    if low  >= (.20):
        print('Low level is Red')
    if grand_total  >= (.20):
        print('Grand Total is Red')    
    if grand_total < (.20) and low < (.20) and high < (.20) and med < (.20):
        print('None')

and if you'd like to use a loop, you can use a dictionary and flag to get it to work:

flag = True
d = {
    'High': high,
    'Medium': med,
    'Low': low,
    'Grand Total': grand_total
}
for i in d:
    if d[i] >= (.20):
        flag = False
        print('{0} level is Red'.format(i))
if flag: print('None')