I am wondering if this is possible. I want to have an infinite while loop but still wont the rest of the code outside the while loop to continue running while the loop is on. like a way to break the while loop after each iteration for instance. i need to find a way for the second print statement to be executed without breaking the while loop completely.
while True:
print('i will loop forever')
print('this code will never be executed because of the while loop')
There are a number of ways to accomplish this, such as threading. However, it looks like you may wish to serially loop for a while, break, then continue. Generators excel at this.
for example:
def some_loop():
i=0
while True:
yield i
i+=1
my_loop=some_loop()
#loop for a while
for i in range(20):
print(next(my_loop))
#do other stuff
do_other_stuff()
#loop some more, picking up where we left off
for i in range(10):
print(next(my_loop))
Related
How would I go about looping these two actions only in the code.
driver.find_element_by_xpath("//*[#id='skipAnimation']").click() time.sleep(1) driver.find_element_by_xpath("// *[#id='openAnother']").click()
I don't want to loop the whole code I want these two codes to repeat until I stop it
Your goal is not really clear: "I don't want to loop the whole code I want these two codes to repeat until I stop it".
Do you expect to end the loop 'manually'?
If so, then you can ask for user input in Python with input().
If my understanding of the problem is correct, you want to run your two functions until you decide to manually stop them running?
I believe a while loop could be used for this task.
You have different options depending if you want to press a key at each iteration, or if you want it to loop until you press a specific key.
Press at each iteration:
while True: # infinite loop
user_input = input("Want to continue? ")
if user_input == "No":
break # stops the loop
else:
# do whatever computations you need
driver.find_element_by_xpath("//*[#id='skipAnimation']").click()
time.sleep(1)
driver.find_element_by_xpath("// *[#id='openAnother']").click()
print('looping')
Now, if you want it to constantly run, until you press a key, there are two options:
while True:
try:
# do whatever computations you need
driver.find_element_by_xpath("//*[#id='skipAnimation']").click()
time.sleep(1)
driver.find_element_by_xpath("// *[#id='openAnother']").click()
print('looping')
except KeyboardInterrupt:
break
Or
import msvcrt
while True:
# do whatever computations you need
driver.find_element_by_xpath("//*[#id='skipAnimation']").click()
time.sleep(1)
driver.find_element_by_xpath("// *[#id='openAnother']").click()
print('looping')
if msvcrt.kbhit():
break
But pay attention to the behavior if you're in a notebook.
I have a problem with loop for game I am writing.
most of game's code is in while loop, the part I am concerned looks more or less like that:
while True:
lista=[]
somenumber=randrange(5,20)
lista.append(somenumber)
break
not a real code but shows idea. I want the list to expand each time the loop runs, but instead the list holds only number from current loop. Any idea how I can do it? I would like the list to expand witch each run of the loop.
You must mive this
lista=[]
Outside of your loop, otherwise you init that variable each iteration. Also you need to delete
break
As it breaks after first iteration. From other hand you need
some logic to stop the loop otherwise you will be spinning till out of memory
Define the list outside of the loop,
Each time it initiates a new list so that your list gets emptied/a new list is defined.
Initialize the list outside while loop.
The list is reinitialized everytime therefore holds only the current iteration value.
Your break statement breaks the loop the first iteration through and your list gets redefined to be empty each iteration. The list should be outside the loop and the loop should only be broken when a certain criteria is met, otherwise it's an infinite loop. This can be accomplished with an if (criteria): break or while (criteria to be met, not yet met):
lista=[]
while True:
somenumber=randrange(5,20)
lista.append(somenumber)
if (some selection statement):
break
Another way to write it, for example if you want 25 items in your list, would be:
lista=[]
while len(lista)<25:
somenumber=randrange(5,20)
lista.append(somenumber)
Try this:
condition = 0 #start
limit = 10 #finish
lista=[]
while condition < limit: #while not yet reached finish
somenumber=randrange(5,20)
lista.append(somenumber)
condition += 1
Thanks guys. I think I know what to do. The game I am doing is an old game from C64, not sure if it was anywhere outside of Poland and in Poland it's title was "Namiestnik" - a text strategy where you were running Roman Colony
Making a simple program that swaps the location of numbers in a loop until they are in ascending order. I want the program to end when the if conditional is never activated within a instance of the for loop. Is there a shorter way to do this without the use of a while true/false or like?
while tf == True:
for i in range(lisLen-1):
tf=False
if listy[i]>listy[i+1]:
tf=True
swap(listy, i, i+1)
Get rid of the variable, and use break instead. Then you can use the else: clause to test this. That clause runs if the loop ended normally instead of with break.
while True:
for i in range(lisLen-1):
if listy[i]>listy[i+1]:
swap(listy, i, i+1)
break
else:
break
Is there an efficient way to break out of a nested loop by having a user simply providing an input at the particular time they want to break out (e.g. press a key)? I have conditional statements in the loops themselves that I can use to break the loops, but if for example I simply want to stop the loops at any time yet still want the rest of the code to run, is there a simple way to do that? To clarify the motivation, I would like to do something like:
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
if (user_has_pressed_key) == True: #a user input that
#can come at any time
#but there should NOT be
#a prompt needed for each iteration to run
break
else:
continue
break
else:
continue
break
I have considered using raw input, but would not want the loops to wait each iteration for the user as there will be numerous iterations. There appear to be some proposed solutions when using different packages, but even these seem to only be Windows-specific. I am running this code on multiple computers so would ideally want it to function on different OS.
You can break out of the nested loops if the user issues a Ctrl+C keystroke, since it throws a KeyboardInterrupt exception:
try:
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
except KeyboardInterrupt:
print("Stopped nested loops")
If you want the loop to break whenever any key is pressed by the user, then you can try this import:
from msvcrt import getch
while True:
key = getch()
if (key is not None):
break
I've got some Python code as follows:
for emailCredentials in emailCredentialsList:
try:
if not emailCredentials.valid:
emailCredentials.refresh()
except EmailCredentialRefreshError as e:
emailCredentials.active = False
emailCredentials.save()
# HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP
# SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW?
# a lot more code here that scrapes the email box for interesting information
And as I already commented in the code, if the EmailCredentialRefreshError is thrown I want this iteration of the for loop to stop and move to the next item in the emailCredentialsList. I can't use a break because that would stop the whole loop and it wouldn't cover the other items in the loop. I can of course wrap all the code in the try/except, but I would like to keep them close together so that the code remains readable.
What is the most Pythonic way of solving this?
Try using the continue statement. This continues to the next iteration of the loop.
for emailCredentials in emailCredentialsList:
try:
if not emailCredentials.valid:
emailCredentials.refresh()
except EmailCredentialRefreshError as e:
emailCredentials.active = False
emailCredentials.save()
continue
<more code>