Restart a function in python - python

My code is in a while True loop.
It basically tries something like captcha.
So what I want is something like this
def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
#break the function
if __name__ == "__main__":
giris()
while 1:
loop()
it can't find the number in dictionary it will break the function and restart the function again because function is in while loop.

Ok found a good way to restart it.
class CustomError(Exception):
def __init__(self, arg):
# Set some exception infomation
self.msg = arg
def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
raise CustomError('Kelime Dictionaryde bulunamadi')
if __name__ == "__main__":
giris()
while 1:
try:
loop()
except CustomError, arg:
print "Can't find in dictionary"

You can literally use break. By using break, you can stop the loop immediately. You will see the use of the return later.
for i in sayilar:
if i in diction:
toplam += diction[i]
else:
return None
break
return True # Anything but None will work in place of True
This goes the same for the while loop:
while True: # Use True instead of 1
loop()
if loop() == None: # The function call is equal to what it returned
break
else:
continue # Optional else statement: continues loop if loop() != None

Related

Python How to iterate through a list of functions

I have a bunch of functions that do x y and z, these functions get executed after an exception has occured. so my problem is that instead of writing the functions one by one i want to create a list of functions and a write a function to iterate through those functions in the list.
If you could show me an example that would be of great help.
here is what i have:
def call_va_funcs(self, stop):
self.disableZüruckVA()
while True:
try:
correct = urllib.request.urlopen("http://192.168.167.12", timeout=10).getcode()
print(correct, "192.168.100.2 is reachable: FAIL")
if correct == 200:
self.enableZüruckVA()
self.exitflag == True
break
except Exception:
print('Preflash')
if self.exitflag == True:
self.enableZüruckVA()
break
self.ping_all_va()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.run_rxtx()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.call_netzteil()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
As you can see here i am repeating the same process over and over again but with a different function. Can anyone help me figure out how to have a list and then just iterate through the bunch of functions.
Thank you
Let's say you have functionA(), functionB() and functionC().
You could put the names of the functions in a list like this:
f_list = [functionA, functionB, functionC]
You can then call these functions one after another:
while True:
# other code here...
try:
#... other code
except:
# ...other code
for func in f_list:
func()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
you could try smth like this
my_methods = []
my_methods.append('ping_all_va')
my_methods.append('run_rxtx')
my_methods.append('next_func')
for cmd in my_methods:
method = getattr(self, cmd)
method()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break

Get user input to stop a while loop

I need a way to stop a loop by getting user input without blocking the loop itself which works cross-platform.
Things I have tried:
processes (closes stdin so I can't use input())
threads (can't kill a thread if the while loop terminates and I no longer need the input())
FLAG = False
def break_main_loop(): # how do I get this to execute?
global FLAG
user_in = input()
if user_in == 'stop':
FLAG = True
return
else:
break_main_loop()
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if FLAG:
break
return # if I return here, I need to cancel break_main_loop's input()
main()
This will work for you and simple to use. Replace main function with this
def main():
# do stuff, e.g. getting other user input()
try:
while True:
stuff()
except KeyboardInterrupt:
print("Press 1 to quit")
return # if I return here, I need to cancel break_main_loop's input()
main()
I'd love to answer your question. You see, once you are in the main-loop, you don't necessarily need to use a FLAG variable, rather, I'd suggest doing something like this :
def break_main_loop(): # how do I get this to execute?
user_in = input()
if user_in == 'stop':
return True # Returning integer 1 also works just fine
else:
return False # Returning integer 0 also works just fine
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if break_main_loop(): # If the user inputs stop, the loop stops via the return statement automatically
return
main()
If you wish to get out of the loop without returning anything else and keep the main() function running for doing stuff:
def break_main_loop(): # how do I get this to execute?
user_in = input()
if user_in == 'stop':
return True # Returning integer 1 also works just fine
else:
return False # Returning integer 0 also works just fine
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if break_main_loop():
break
#continue doing stuff
main()
Now, there's a better way to break out of the loop without using the helper function break_main_loop(), and that's done like so:
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if str(input("Do you wish to continue:[y/n]")) == 'n':
break
#continue doing stuff
main()
This lets you get rid of the helper function completely.
I hope this answer was helpful. :D
try this:
class new_game:
start_game = True
# end_game = False
def break_main_loop(self): # how do I get this to execute?
print("game is ending!")
def stuff(self):
print("this is stuff happening....now...game is: ", self.start_game)
def game_loop(self):
user_in = int(input("enter '2' to end game or '1' to keep playing:" ))
if user_in == 1:
self.stuff()
self.game_loop()
else:
return self.break_main_loop()
Test_game = new_game()
Test_game.game_loop()

Calling a method from farther down the stack

Ok I have a code that's basically this....
def create():
#long list of print statements
m_commands()
def get_desc():
#print statement
m_commands()
def m_commands():
while close != True:
input = input(str(">>>"))
If inp == "close" or "quit":
close = True
If inp == "create":
create()
If inp == "describe":
get_desc()
m_commands()
I need to call m_commands() in create() and get_desc() to continue continuity. Is this possible. Sorry in advance, I don't know how to put code in a spoiler thingy. Thanks!
def create():
#long list of print statements
print("hello")
m_commands()
def get_desc():
#print statement
print("world")
m_commands()
def m_commands():
close=False
while close != True:
inp = input(str(">>>"))
if inp == "close" or "quit":
close = True
if inp == "create":
create()
if inp == "describe":
get_desc()
m_commands()
This is working for me though.

How to continue the program even after evaluating the condition to true in if else loop in python?

I am implementing the scenario in which i have multiple if,elif,else loops.My problem is when the condition met ,its coming out of the program and exits the program .
Expected Behavior - After successful completion it should not exit but rather again show me the options to select .Only after pressing something like cntrl+c it should exit out the program.
class Manager:
def __init__(self):
self.not_useful_tests = []
self.sdsf
def sdsf(self):
try:
input = raw_input()
if input == 'x':
self.not_useful_tests.append(0)
else:
if input == 1:
verify = self.ABC()
return verify
if input == 2:
verify = self.xyz()
return verify
if input == 3:
verify = self.hyg()
return verify
if input == 4:
verify = self.fgh()
return verify
if input == 5:
verify = self.qwe()
return verify
except KeyboardInterrupt as e:
print "Exception caught : " + str(e)
return None
How to achieve this beahvior ? What to add in the code so as to achieve the task ?
To repeat something while some condition is true, use a while loop:
while True:
input = raw_input()
if input == 1:
return 'some value'
if input == 2:
return 'some other value'
If you don't want to return a function result, but rather want to continue execution outside of the loop, i.e. 'break out of the loop' use break:
while True:
input = raw_input()
if input == 1
print('doing something')
break
if input == 2
print('doing something else')
break
print('Continuing here')
And if that's what you want, you can also set a condition to end the loop like this:
result = None
while result is None:
input = raw_input()
if input == 1:
result = 'x'
if input == 2:
result = 'y'
print('will continue here if result has a value')

How do I return to a while loop from the main code

I'm looking for a way to return to a while loop after it is done.
Basically, in my main code, at the beginning, there is a while loop that I want to do for x amount of times and then exit out and execute some other code. If certain values are met, return to the while loop at the top of the main.
Here is the code that I wrote but once the while loop is finished it just stops.
t = 0
def main():
global t
try:
while t < 3:
distance = Tank_Measurement()
if distance > 5 and distance < 100:
print ('Distance:',distance ,'cm')
Pumping_to_Growbed()
time.sleep(2)
draining_Selenoid()
t = t + 1
else:
print ('Distance:',distance ,'cm is out of range')
time.sleep(1)
Tank_Measurement()
t = t + 1
return
distance = Tank_Measurement()
distance2 = growbed_Measurement()
if distance < 5 and distance2 < 5:
print ('Water level in main tank low')
print ('Filling up main tank')
time.sleep(1)
Pumping_to_mainTank()
t = 0
else:
t = 0
except KeyboardInterrupt:
print ('Exiting program gracefully')
for i in range(3,0,-1):
time.sleep(1)
sys.stdout.write(str(i)+' ')
sys.stdout.flush()
finally:
GPIO.cleanup()
main()
Put the entire body of main() inside another another while loop:
def main():
keep_looping = True
while keep_looping:
... original code here
if some_condition:
keep_looping = False
once the while loop is finished it just stops
That is because you have a return as the next statement after while. So it returns to the point where you called main(), which then is the last line of your code, no further statements or code after that.

Categories