Breaking out of nested loops with user input - python

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

Related

Looping two actions

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.

Is there a conditional that runs if an if statement does not activate within a loop?

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

python pause infinite loop for code outside loop to be executed

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))

Best way to quit a python programme?

I feel like an idiot asking this but is doing quit() the best way to terminate a python programme? Or is there a better way that could gradually stop all while True loops ect instead of just instantly stopping it all? Once again, I feel like an idiot asking this but I'm just curious.
I don't know why you don't want to use quit() but you can use this:
import sys
sys.exit()
Or this:
raise SystemExit(0)
To halt a while loop you can use the break statement. For example:
while True:
if True:
do something #pseudocode
else:
break
The break statement will immediately halt the while loop as soon as the else statement is read by python
You can use the break statement to stop a while loop. Eg:
while True:
if True:
<do something>
else:
break
Generally, the best way to end a Python program is just to let the code run to completion. For example, a script that looks for "hello" in a file could look like this:
# import whatever other modules you want to use
import some_module
# define functions you will use
def check_file(filename, phrase):
with open filename as f:
while True:
# using a while loop, but you might prefer a for loop
line = f.readline()
if not f:
# got to end of file without finding anything
found = False
break
elif phrase in line:
found = True
break
# note: the break commands will exit the loop, then the function will return
return found
# define the code to run if you call this script on its own
# rather than importing it as a module
if __name__ == '__main__':
if check_file("myfile.txt", "hello"):
print("found 'hello' in myfile.txt")
else:
print("'hello' is not in myfile.txt")
# there's no more code to run here, so the script will end
# -- no need to call quit() or sys.exit()
Note that once the phrase is found or the search comes to the end of the file, the code will break out of the loop, and then the rest of the script will run. Eventually, the script will run out of code to run, and Python will exit or return to the interactive command line.
If you want to stop a while True loop, you could set a variable to True and False, you could even work with a counter if you loop has to stop after a specific amount of loops.
for example
x = 0
y = True
while y == True:
<do something>
x = x + 1
if x == 9:
y = False
just a quick example of what you could do, without using a while loop(basically what i wrote above, but then in 1 line.)
x = 10
for i in range(x):
<do something>
To stop a program, I normally use exit() or break.
I hope this somehow helped you, if not; please comment and I'll try helping you!

How to stop code execution of for loop from try/except in a Pythonic way?

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>

Categories