I have a section of code with several nested if
statements that must be in a certain order. However, one of those ifs is optional. That is, if we do test condition1
, we must do it first, but we can skip it if the user prefers. One can do this the following way:
option = True #user can toggle this
if option:
if condition1:
if condition2:
if condition3:
print("Hello World")
else:
if condition2:
if condition3:
print("Hello World")
However, this reuses a lot of text. What is the best way to do this?
>Solution :
The effect of this:
if condition1:
if condition2:
if condition3:
print("Hello World")
Is the same as:
if condition1 and condition2 and condition3:
print("Hello World")
Similarly, to replace your entire example:
if option:
if condition1:
if condition2:
if condition3:
print("Hello World")
else:
if condition2:
if condition3:
print("Hello World")
This makes more sense:
if ((not option) or condition1) and condition2 and condition3:
print("Hello World")
Since you want the same to happen in either case, which is to print that message.
Have a search for "Python boolean operators" to learn more about how not
, and
and or
work.
Note that the parentheses are technically not required in this case, since and
takes precedence over or
, and not
takes precedence over either – but since you’d have to remember that and there’s no real impact from the parentheses, I figured putting them in and leaving them in makes sense.