Home > Software engineering >  Evaluate 2 if statements and a else condition
Evaluate 2 if statements and a else condition

Time:08-07

I have outer and inner if statements and one else condition. Can I evaluate the two ifs without rewriting the exact same else?

a = 1

if a == 1:
     b = a * 5
    if b < 3:
        print(b)
else:
    print(a)

Basically, I'd like to evaluate the else if the inner if condition is not met.

CodePudding user response:

Updated answer after clarification of the question.

You can just delay taking the action until after the if/else:

a = 1

to_print = a
if a == 1:
    b = a * 5
    if b < 3:
        to_print = b

print(to_print)

CodePudding user response:

a = 1
b = 2

if a == 1:
    print(a)

else if b == 1:
    print(b)

else:
    print(c)

Maybe you are looking for this?

CodePudding user response:

Indent it the same amount as that if statement:

if a == 1:
    if b == 1:
        print(b)
    else:
        print(a)
else: 
    print(b)

Update from comments:

if a == 1 and b != 1: 
    print(a)
else:
    print(b)

CodePudding user response:

Yes you have to use AND OPERATOR (&&), Because the inner condition get control only if a == 1 and inner if returns response only if b == 1 So, we have to make them one using AND Operator

a=1
b=2
if a==1 and b == 1 :
   print(b)
else:
   print(a)
  • Related