if, elif and else.. priority and chains - python

I always had this curiosity about Python and I can't find a clear answer, maybe someone can help me
what is the "if", "elif" and "else" priority and way of working?
if I do:
if conditionA:
do something
elif conditionB:
do something else
else:
do something else
does the "else" check the condition in "elif" or both conditions "if" and "elif"?
is there any interesting order in which they can be used (e.g. if, else, elif, else etc.) ?
thanks

else is the catch-all after all the if and elif statements were false. Putting it in the middle would be a syntax error.
Don't think of the else "checking the conditions." Think of it as the control flow never even reaches the else if the others were true. The same is true for multiple elif.
Consider this:
if False:
print 'first'
elif True:
print 'second'
elif True:
print 'third'
Even third won't print, because the second one was true. It doesn't matter that the third was true, because it's not even evaluated.
This can have some side effects too, if you're calling functions:
if send_email(to_coworker):
pass
elif send_email(to_boss):
pass
Assuming the function returns True if it succeeds, the email to your boss will only send if the email to your coworker fails, even though the function would need to be called to evaluate the elif condition

They're processed in the order that they're encountered in the file.
if True:
# Always executes.
elif False:
# Is never checked.
else:
# We never get this far, either.
As soon as the first condition that evaluates True is encountered the corresponding block of code is executed. Additional conditions aren't checked.

They don't have priorities for itself, what really matters is the order, so the first condition will be checked and if the first condition is False than the second condition is checked and so on until any condition is True or it executes the else statement if and only if all conditions where False
In your example if conditionA is True then the code inside the if statement will be executed and the elif and else conditions will not matter at all.
If conditionA is False and conditionB is True than the code inside the elif statement will be executed.
Finally only when the conditionA and conditionB is False then the code inside else block will be executed

Related

How to make a loop that keeps cheking if theres a certain class

Hello I'm trying to make a loop that keeps searching for a class with "buy" and if it finds it needs to refresh until it can't find it anymore and then it runs the rest of the code. I'm using selenium and python help would be much appreciated. Thanks in advance
foundButton = False
while not foundButton:
driver.find_element(By.CLASS_NAME, "buy")
if (driver.find_element(By.CLASS_NAME, "buy")):
time.sleep(1)
driver.refresh()
driver.find_element(By.CLASS_NAME, "buy")
else:
foundButton = True
While not true is the actual loop condition. The value must be true.
while(condition) or if(condition) implies do the action if condition evaluates to true. while not means do it if the condition is false. but because your initial value is false, the not negates it to true and ultimately the loop bever executes because the falseButton is false and the loop condition interprest as true always.
I always advise against using boolean values to control loop conditions because especially in python it is easy to confuse outer logic with inner logic. What I mean is that
while (condition)
while [not (condition)]
No matter what the outcome is, for the while to proceed, the cumulative outcome must be true always.

Python if, elif, else does not run if, elif, or else statement

I'm using an if, elif, else statement in a method. When I run the code it doesn't run the if, elif, or else, but when I comment out the elif statement it defaults to the else as expected.
def message(response):
args.pop(0)
if com_text == "trivia":
# triviaActive will be False
if triviaActive:
# Performs action
return True
# args[0].lower() is not equal to 'start'
elif args[0].lower() == "start" and not triviaActive:
# Performs action
return True
# So it should defaults to this else
else:
# Performs action
return True
I added some comments above the chain of if, elif, and else statements that's giving me the unexpected results. Instead of it defaulting to the else statement, as it should in this situation, it just returns from the method without running the rest of the method. I even tried using print statements inside of the if, elif and else statements, but the program doesn't run them.
(edit)
I simplified my if, elif, and else. Even with this simplified version I still have a problem with my elif. Also I want to mention that I use the pop method to pop a value off of args and makes it empty which could be the issue.
Test the code by replacing
com_text == "trivia":
With
True:
None of your conditions will run if that does not hold.
If everything seems fine after that change, then it could be that your editor does not like your blank line spacing. As a sanity check, remove the blank lines and see if it works as expected (some editors may not work if the blank line does not have proper indentation, and you seem to have no indentation on your blank lines).

How else part work in continue statement?

I'm not sure how the continue statement is interpreted when it is inside a for loop with an else clause.
If the condition is true, the break will exit from a for loop and else part will not be executed. And if the condition is False then else part will be executed.
But, what about continue statement? I tested it seems that the after the continue statement is reached, the else part will be executed. Is this true?? Here is a code example:
# when condition found and it's `true` then `else` part is executing :
edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")`
If I remove "spam" from the list, now the condition is always false and never found but still the else part is executed:
edibles = ["ham","eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")
With a for loop in Python, the else block is executed when the loop finishes normally, i.e. there is no break statement. A continue does not affect it either way.
If the for loop ends because of a break statement, then else block will not execute. If the loop exits normally (no break), then the else block will be executed.
From the docs:
When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.
I always remember it because of how Raymond Hettinger describes it. He said it should have been called nobreak instead of else. (That's also a good video that explains the usefulness of the for-else construct)
Example:
numbers = [1,2,3]
for number in numbers:
if number == 4:
print("4 was found")
break
else:
print("4 was not found")
When you run the above code, since 4 is not in the list, the loop will not break and the else clause will print. If you add 4 to the list and run it again, it will break and the else will not print. In most other languages, you would have to add some sentinel boolean like found and make it True if you find a 4, then only print the statement after the loop if found is False.
Your else part will be executed in both cases.
else part executed when loop terminate when condition didn't found.Which is what is happening in your code. But it will also work same without continue statement.
now what about break statement's else part, Break statement's else part will be executed only if:
If the loop completes normally without any break.
If the loop doesn't encounter a break.

Flow control after breaking out of while loop in Python

I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
now do a thing once, but only if you never broke out of the loop above
What I've ended up doing works, but feels off somehow:
def pseudocode():
while some condition is true:
do some stuff
if some condition is met:
some_condition_met = True
break out of the while loop
if some_condition_met is False:
do a thing
Is there a better way?
You're looking for while-else loop:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke out of the loop above
From docs:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite.
Use an else clause to the while loop:
while some_condition:
do_stuff()
if a_condition_is_met:
break
else:
executed_when_never_broken
See the while statement documentation:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
If you think about it, you might already have a perfectly good condition to use without setting a flag: the condition at the top of the while loop (or, rather, the not of it). Assuming you don't change the truthiness of your condition during the same iteration as a break, this gives you:
while something:
do_stuff()
if something_else:
break
if not something:
more_stuff()
This makes sense if you think of while as a repeated if: instead of happening once, a while keeps going until the condition becomes falsey.
But, like the other answers have mentioned, the analogy goes further: just like you don't have to spell all your ifs as
if a:
a_stuff()
if not a:
b_stuff()
while accepts an else that is executed if the condition at the top is tested and found to be falsey. So,
while something:
do_stuff()
if something_else:
break
else:
more_stuff()
And, same as the if/else case, this doesn't imply any further tests of the condition than what would happen anyway. In the same way that an else attached to if a won't run if the true-branch makes a falsey, an else attached to a while will never run after a break since that explicitly skips ever checking the condition again. This makes the else: equivalent to a decicated flag in every case.
This also extends to for loops, even though the analogy breaks - but it executes under similar enough rules: the else is run if the loop ends by having run its course rather than hitting a break.

strange while statement behaviour?

I cannot figure out why the following statements dont work.
randomKey = random.choice(list(topic.keys()))
randomValue = random.choice(topic[randomKey])
current = "-" * len(randomValue)
while current != randomValue:
(statements)
else:
(statements)
However, if i alter the 1st line to
while current == randomValue:
the statement after 'else' executes correctly. Otherwise, the statement after 'else' does not execute. Any idea why what may be causing the strange behaviour? Full code has been excluded for it will run through this entire page.
It is part of the Python grammar. From the documentation:
This [a while statement] repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
So in the first case, it must be that the while condition never evaluates to false, while in the second it eventually does. Note that explicitly breaking out of the loop will not execute the else clause.
else, when used with while, runs after the while expression evaluates to a falsy value if the while loop finishes by the expression being false, instead of being broken out of by a break statement (or execution leaving the function via a return or raise-ing an exception). Your while condition in your second example must fail, so there's no opportunity for a break to occur, the function to return or an exception to be thrown, so the else statements will always run.
docs for while

Categories

Resources