In python, is there a difference between say:
if text == 'sometext': print(text) if text == 'nottext': print("notanytext")
and
if text == 'sometext': print(text) elif text == 'nottext': print("notanytext")
Just wondering if multiple if
s could cause any unwanted problems and if it would be better practice to use elif
s.
Summary: By using an ELSE IF structure instead of multiple IF we can avoid “combined conditions” ( x<y && y<z ). Instead we can use a simplified condition (y<z). Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE.
If statements are executed independent of one another; each one will run. Else if statements only execute if the previous if s fail.
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.
There can be multiple 'elif' blocks, however there is only 'else' block is allowed. 2. Out of all these blocks only one block_of_code gets executed. If the condition is true then the code inside 'if' gets executed, if condition is false then the next condition(associated with elif) is evaluated and so on.
Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With