Break inside a function with for - python

(Python 3.10.4)
I have a for condition and inside this for a have a function that need a break and go back to the top like "continue" do, but i can't use break outside a loop, how can i go back to the top of the code? I will use this function so many times after and i don't want to have so many if in my code
import time
def function1():
if pyautogui.locateCenterOnScreen('file.png')
pyautogui.moveTo(x=612, y263)
time.sleep(1)
break
How can i break the code in this case:
for c in range (0,10):
print('begin for')
#FUNCTION
function1():
#
#
#REST OF THE CODE

It's hard to imagine what you meant by 'break the code' with your incorrect code indentations. I guess you meant to break the for loop
when the function breakes.
Use a variable out side the function to indicate when you're done with your function.
And check for the value of the variable within the for loop to break or pass
br = 0
def function1():
if pyautogui.locateCenterOnScreen('file.png')
pyautogui.moveTo(x=612, y=263)
br = 1
time.sleep(1)
return 0
for c in range (0,10):
print('begin for')
#FUNCTION
function1()
if br == 1:
break
else:
pass
#
#
#REST OF THE CODE

Related

SyntaxError: 'break' outside loop when I use it in loop [duplicate]

This question already has answers here:
break and continue in function
(4 answers)
Closed 12 months ago.
Problem
Hi, I am have a problem. Well, I know that I can't use break outside the loop but I use it in loop and still get an error.
What I do
I create a function that have a command break and use it in loop. I get an error. I can't do something like this:
function()
break()
because my function have an if statment, for example:
do somthing
if that:
break
Code
def destroy():
i = o.index(rect)
MAPh[i] -= 1
if MAPh[i] <= 0:
del o[i]
del MAP[i]
del MAPxy[i]
del MAPh[i]
break
for a in range(len(MAP)):
...
destroy
The fact that a function is called from a loop doesn't mean you can break the loop from it. The break statement must be directly in the scope of a loop, not implicitly.
If you want to break the loop when a condition in the function is fulfilled, you can change the function to return an indicator for the loop to break:
def destroy():
...
if condition:
return True
return False
for a in range(len(MAP)):
...
if destroy():
break
Break or continue are part of loops. You can use them if there is a loop in your code. If you just use conditional statements you can't and you don't need to use break. Just remove it or put your code into loop.

It is possible to not increment count in for loop - Python

it is possible to not increment count in for loop in case an error happen, like this example
for i in range(10):
try:
print(i)
except: # if and error happen in i == 5 the next iteration will be 5 not 6
pass
I want to repeat the same iteration when the error happen. And thanks in advance.
When you use for...in there's no way to avoid going to the next item in the iteration when the loop repeats.
You can use a nested loop to keep trying with the same value of i until you don't get an error:
for i in range(10):
while True:
try:
print(i)
break
except:
pass
Maybe wrap all into a while loop:
for i in range(10):
while True
try:
# whatever you have to do
print(i)
break
except:
pass
Since Python's for loop is technically a foreach loop you should use a while instead of for for more control.
i = 0
while i<10:
try:
#Do stuf
i += 1
except:
pass
If an error happens before i += 1 it will not be incremented.

How to make this loop?

How would I loop this?
def start():
print('welcome to reduce that fraction')
n=int(input("please enter numerator"))
m=int(input("please enter denominator"))
r=2
while (n%r!=0):
for y in range(2,10,1):
a=n%r
r=r+1
while (m%r!=0):
for x in range(2,10):
b=m%r
r=r+1
print(n/r,"/",m/r)
print("Goodbye")
start()
I am stuck on how to loop it back to the beginning. Any ideas?
I'm assuming you want the function "start()" to re-run after completing. In that case, here's what I'd do:
while True:
start()
This is a boolean while-loop that always holds (Python implicitly parses "while True" as "while True == True"), so the function will keep looping.

Get stuck in a 'while True' loop python

I just learned about break and return in Python.
In a toy code that I wrote to get familiar with the two statements, I got stuck in a loop, but I don't know why. Here is my code:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
I'm new to programming, any suggestions will be appreciated.
With the for-else construct you only enter the else block if the for loop does not break, which your for loop always does because i inevitably becomes 3 with your range generator. Your infinite while loop is therefore never able to reach the return statement, which is only in the said else block.
nvm I'm super wrong here
First of all, when you define a function in Python, any code that belongs in the function should be in the same indentation block. With this in mind, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
The next problem I see is that your else statement isn't correctly formatted with an if statement. If you mean for it to go on the 2nd if statement, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
This is only formatting. But in this example, the code would only run once because it immediately returns and exits the function.
I think this may be a better example of using both break and return:
def break_return(value):
for i in range(5):
print(i)
if i == 3:
break #This exits the for loop
if i == 4:
print("This won't print!")
#Won't print because the loop "breaks" before i ever becomes 4
return value * 2 #Returns the input value x 2
print(break_return(30)) #Display the return value of break_return()
This demonstrates how break exits a for loop and how return can return a value from the function.
The output of the code above is:
0 #Value of i
1 #Value of i
2 #Value of i
3 #Value of i
60 #The value returned by the function
Glad to hear you're learning Python! It's a lot of fun, and super useful.

how to exit try loop after code succeed?

my code below tries to execute a function x but because x takes time to build, i need to sleep until it is built then call it. So it usually takes me about 300s to build. When i run the code below, it will loop through the try loop about 3 times but print 0 every time it pass through the except code.
Is it right to put the print x (for when code succeeds and i break) outside the for loop like below or somewhere else? Also, how do i make i print the number of time it is trying instead of 0?
for i in range(0,10):
while True:
try:
x = my_get_fuction
except:
print "error"
print i
time.sleep(100)
continue
break
print x
Your while loop doesn't seem to be related to your design. Try this:
for i in range(0,10):
try:
x = my_get_fuction
except:
print "error"
print i
time.sleep(100)
continue
break
print x
This code will loop a maximum of 10 times, sleeping each time for 100s. If the assigned x = my_get_function doesn't complete by 1000s or so, then the loop gives up.

Categories