Python: While Loop Check Throughout Loop if True - python

I have a very simple problem: I have made a while loop, and in the middle of it, set the initial condition to false. This, however, does not stop the loop and runs entirely through, (somewhat obviously,) until it attempts to unsuccessfully go through again. Here is a simplified construction of what I have.
while(a):
print("hi")
a = False
print("bye")
This returns:
hi
bye
Again I would like to only return hi; I want the loop to continually check if its satisfied.
Any help greatly appreciated.

Use:
return, or break
while a:
print('hi')
a = False
if not a:
break
print('bye')
In a function or loop, when something is returned, the function or loop terminates. You could also return True, or break which is a specific way to 'break' out of a loop.

Since the condition is true to start with (by design), the body of the loop will execute at least once. The fact you do something in the body of the loop to make the loop condition false doesn't stop the current iteration. It just means there won't be a next iteration after this one is done.
So if you want to get out in the middle of the current iteration, then you need to use break, return, or something more sophisticated like #inspectorG4dget's suggestion.

while(a):
print("hi")
a = False
if a:
print("bye")
OR
while(a):
for s in ["hi", "bye"]:
if a:
print(s)
if someCondition:
a = False

Related

How do I run a conditional statement "only once" and every time it changes?

I might be asking a simple question. I have a python program that runs every minute. But I would like a block of code to only run once the condition changes? My code looks like this:
# def shortIndicator():
a = int(indicate_5min.value5)
b = int(indicate_10min.value10)
c = int(indicate_15min.value15)
if a + b + c == 3:
print("Trade posible!")
else:
print("Trade NOT posible!")
# This lets the processor work more than it should.
"""run_once = 0 # This lets the processor work more than it should.
while 1:
if run_once == 0:
shortIndicator()
run_once = 1"""
I've run it without using a function. But then I get an output every minute. I've tried to run it as a function, when I enable the commented code it sort of runs, but also the processing usage is more. If there perhaps a smarter way of doing this?
It's really not clear what you mean, but if you only want to print a notification when the result changes, add another variable to rembember the previous result.
def shortIndicator():
return indicate_5min.value5 and indicate_10min.value10 and indicate_15min.value15
previous = None
while True:
indicator = shortIndicator()
if previous is None or indicator != previous:
if indicator:
print("Trade possible!")
else:
print("Trade NOT possible!")
previous = indicator
# take a break so as not to query too often
time.sleep(60)
Initializing provious to None creates a third state which is only true the first time the while loop executes; by definition, the result cannot be identical to the previous result because there isn't really a previous result the first time.
Perhaps also notice the boolean shorthand inside the function, which is simpler and more idiomatic than converting each value to an int and checking their sum.
I'm guessing the time.sleep is what you were looking for to reduce the load of running this code repeatedly, though that part of the question remains really unclear.
Finally, check the spelling of possible.
If I understand it correctly, you can save previous output to a file, then read it at the beginning of program and print output only if previous output was different.

Recalling a function iteratively

I have a question about recalling my function within a loop.
Below is my code:
List_new = myfunction()
for items in List_new:
if(my condition is TRUE):
Execute some commands
if(my condition is FALSE):
recall myfunction()
My problem is that I am loading "List_new" using myfunction(). How can I change "List_new" iteratively when my condition is False. I want to reload the function especially when the condition is FALSE. This means I keep calling the function until it is false and then execute the final output from myfunction().
Thank you in advance for your help.
I am going to assume the list generated by myfunction() is a constant size.
You can use a while loop:
List_new = myfunction()
index=0
while index < len(List_new):
items = List_new[index]
if(my condition is TRUE):
#Execute some commands
i+=1
if(my condition is FALSE):
List_new = myfunction()
Keep in mind that this solution will have an infinite loop if myfunction() continuously generates false values. If you can guarantee that all values will eventually be True then it should always terminate.

First script for automation of instagram , how to loop an else statment inside a for loop?

Hi everyone first time poster long term reader.
my problem is I want an else statment to loop inside a for loop.
I want the else statment to loop until the if statment above it is met?
can anyone tell me where I am going wrong I have tried so many diffrent ways including while loops inside if statments cant get my head round this ?
edit changed the code to a while loop not on prunes suggestion but cant escape the while loop
for url in results:
webdriver.get(url)
try:
liked = webdriver.find_elements_by_xpath("//span[#class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" and #aria-label=\"Unlike\"]")
maxcount = 0
while not liked:
sleep(1)
webdriver.find_element_by_xpath('//span/button/span').click()
numberoflikesgiven += 1
maxcount += 1
print'number of likes given : ',numberoflikesgiven
sleep(2)
webdriver.find_element_by_link_text('Next').click()
if maxcount >= 10:
print('max count reached .... moving on.')
continue
else:
print ('picture has already been liked...')
continue
Yes, you very clearly wrote an infinite loop:
while not liked:
... # no assignments to "liked"
You do not change the value of liked anywhere in the loop. You do not break the loop. Thus, you have an infinite loop. You need to re-evaluate liked on each iteration. A typical way to to this is to duplicate the evaluation at the bottom of the loop
sleep(2)
webdriver.find_element_by_link_text('Next').click()
liked = webdriver.find_elements_by_xpath(
"//span[#class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" \
and #aria-label=\"Unlike\"]")
Also note that your continue does nothing, as it's at the bottom of the loop. Just let your code reach the bottom naturally, and the whilewill continue on its own. If you intended to go to the next iteration offor url in results, then you need tobreakthewhile` loop instead.

or condition in while loop python

Does or condition work in a while loop in python? I can't seem to make it work. This is the sample of how my code works.
newslot = 3
moved = False
while newslot > 0 or moved != True:
enabled = query something on the database where slot = newslot
if enabled:
print 'do something here'
moved = True
else:
newslot-=1
print 'slot disabled'
So when the newslot gets to value of zero it still proceeds to go inside the while loop.
I seem to be missing something here.
or is working as should be expected. A while loop will continue until its condition is false. If its condition is two separate conditions connected with an or, it will only be false when the two conditions are both false.
Your loop will continue repeating until moved is false and newslot is <= 0. I'm guessing you actually want to use and in this case, as you want the loop to stop once either condition is met.

Is the `else:` correct/necessary in this Python program?

Is the line of else: correct/necessary in this Python program?
from random import randrange
for n in range(10):
r = randrange(0,10) # get random int in [0,10)
if n==r: continue # skip iteration if n=r
if n>r: break # exit the loop if n>r
print n
else:
print "wow, you are lucky!\n"
if n<9:
print "better luck next time\n
From the documentation:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement
So yes, it's correct in your example. Although I've never been a fan of it, using an else clause on a loop makes code confusing at first, I'd rather use a boolean flag for achieving the same effect. IMHO else should be used only for conditionals.
from random import randrange
for n in range(10):
r = randrange(0,10)
if n=r: continue # there should be ==
if n>r: break
print n # should be "\n" ?
else:
print "wow, you are lucky!\n" # Yes, you are! Your python interpreter can make miracles :). Try to run me.append(SexyChick(10)) and let's see what happens!
for...else construct is actually valid. else branch is executed if the loop has not been terminated by break. Look here.

Categories