How to loop 2 functions in python? - python

I have 2 functions that I need to call each other based on user settings. That is, if a user has repeat turned on it just needs to keep going until manually stopped, which I have a button for. How can I do this without causing an infinite loop error that crashes the program?
def T1_Timer(list):
msg = list[0]
global t1
T1_List = list
t1 = threading.Timer(MultiTimer2Settings.T1_Time, msg)
while t1.is_alive():
if not t1.is_alive():
return
else:
time.sleep(1)
Parent.SendTwitchMessage(msg)
T1_List.pop(0)
return T1_List
def DoRun1():
T1_List1 = []
T1_List2 = []
while not StopPressed:
T1_List1 = CheckList1(T1_List2)
T1_List2 = T1_Timer(T1_List1)
return
StopPressed = False
def StopButton():
global StopPressed
StopPressed = True
return
def CheckList1(T1_List=[]):
global t1
t1 = threading.Timer(MultiTimer2Settings.T1_Time, "")
if not t1.is_alive() and len(T1_List) <= 0:
if MultiTimer2Settings.T1M1_Enabled:
T1_List.append(MultiTimer2Settings.T1M1)
if MultiTimer2Settings.T1M2_Enabled:
T1_List.append(MultiTimer2Settings.T1M2)
if MultiTimer2Settings.T1M3_Enabled:
T1_List.append(MultiTimer2Settings.T1M3)
if MultiTimer2Settings.T1M4_Enabled:
T1_List.append(MultiTimer2Settings.T1M4)
if MultiTimer2Settings.T1M5_Enabled:
T1_List.append(MultiTimer2Settings.T1M5)
return T1_List

Just use a while loop:
stopButtonPressed = False
var1 = <initial value>
while not stopButtonPressed:
var2 = function1(var1)
var1 = function2(var2)
Instead of each function calling the other, they should return the value that they would pass to the other function. You can then put these in variables and pass them in the successive calls.

something like this
Break = 0
Function1():
test = 12
print test
return
Function1():
test1 = 13
print test2
return
while Break < 15:
Break += 1
Function1()
Function2()
calling another function using one function will not be in the loop therefore doing this is the simplest option
try running it!

Related

Python loop in Functions

This is my nested functions code
def get_id():
for i in range(1,100):
pass
return i
def get_id_mysql(x):
print(x)
variable = get_id()
get_id_mysql(variable)
this function get_id return ( output : 1 ) and loop stop.. how can I hand over full loop? I mean 1,2,3..99
I Found solutions
def get_id():
t = []
for i in range(1,100):
t.append(i)
return t
def get_id_mysql(x):
for i in x:
print(i)
variable = get_id()
get_id_mysql(variable)

How to break out of a for loop using a function?

I'm running an if action defined in a function on a list of elements using a for loop. There is a secondary action within the first action. I want the for loop to stop once the action is successful the first time. Below is sample code to demonstrate:
my_list = [99, 101, 200, 5, 10, 20, 40]
def action(x):
if x >= 100:
print('It is finished')
over_100 = True
return over_100
def action2(x):
x += 1
action(x)
over_100 = False
for number in my_list:
action2(number)
if over_100:
break
I want the for loop to stop at the first instance of >=100. For example, it should add 1 to 99 (first element of the list) and then stop everything. Instead, it is printing "It is finished" 3x because it loops through the whole list.
You can make the function return a value and check the value in the loop. And you can use break to break out of the loop.
list_of_scopes = [scope1, scope2, scope3, etc.)
def action_function():
return 'TEST' in xxxxx
for scope in list_of_scopes:
found = action_function()
if found:
break
As of Python 3.8 you could even use the walrus operator which makes for more readable code:
for scope in list_of_scopes:
if found := action_function():
# optionally do something with `found`
break
A totally different approach to show what I meant in my comment on the question:
from contexlib import suppress
class StopProcessing(StopIteration):
pass
def action_function(param):
if 'TEST' in param:
print('TEST is found!')
raise StopProcessing
with suppress(StopProcessing):
for scope in list_of_scopes:
action_function()
I think you are looking for global.
Global tells your function's scope to not create a new variable over_100 but instead re-use an over_100 that was declared in a higher scope.
I do prefer the other answers that return a value instead of polluting global scope. Whatever works!
my_list = [99, 101, 200, 5, 10, 20, 40]
over_100 = False
def action(x):
global over_100
if x >= 100:
print('It is finished')
over_100 = True
def action2(x):
global over_100
x += 1
action(x)
if over_100:
return
# here is more work for action2 that you skip when over_100
for number in my_list:
action2(number)
if over_100:
break
Output:
It is finished
list_of_scopes = [scope1, scope2, scope3, etc.)
def action_function(param):
found = False
if 'TEST' in param:
print('TEST is found!')
found = True
return found
for scope in list_of_scopes:
result = action_function(scope) # or whatever parameter
if result:
break

Decrementing Function Arguments (PYTHON)

I'm calling functions similar to those that follow, inside a loop:
def bigAnim(tick,firstRun):
smallAnim(x,y,duration)
#more anims and logic...
def smallAnim(x, y,duration):
duration -= 1
if duration != 0:
Anim.blit(screen,(x ,y))
Anim.play()
else:
Anim.stop()
loopedOnce = True
return loopedOnce
Now say I were to call the smallAnim inside the big anim as follows:
def bigAnim(tick,firstRun):
smallAnim(0,50,5)
smallAnim is now being called indefinitely, as duration will never go lower than 4 (being reset to 5 every time it's called in the loop). What would be the best way to solve this problem?
You need to do the counting in bigAnim and only call smallAnim() when the value is greater than zero.
Or you can return the current duration:
def bigAnim(tick,firstRun):
duration = smallAnim(x,y,duration)
#more anims and logic...
def smallAnim(x, y, duration):
duration -= 1
if duration > 0:
Anim.blit(screen,(x ,y))
Anim.play()
return duration
Your underlying problem is Python does pass the references to the variables, but integers are immutable.
This is a little easier to understand with strings:
The function
def foo(s):
s = " world"
will only modify s local to the function if you call foo("hello"). The typical pattern you'll see instead is:
def foo(s):
return s + " world"
And then ... print foo("hello")

Python decorator TypeError 'object is not callable'

I am trying to get myself familiar with decorators.
This is a program I created to do so, but it keeps giving me an TypeError: 'int' object is not callable error, which I don't know how to fix.
#Filename: decorator_practice.py
def add(x):
def add_1():
add_1 = x() + 1
return add_1
def minus(x):
def minus_1():
return x() - 1
return minus_1
def multi(x, times=2):
def multi_2():
return x() * 2
def multi_3():
return x() * 3
def multi_4():
return x() * 4
if times == 2:
return multi_2
elif times == 3:
return multi_3
elif times == 4:
return multi_4
else:
return "Please enter times between 2 and 4"
def create_x():
x = input('Give variable x a value: ')
return x
add(create_x()())
I run this and type: 5
Can anyone help me? Thanks!
Your create_x function returns an integer:
def create_x():
x = input('Give variable x a value: ')
return x
so create_x()() is never going to work.
Part of the problem is that you've used poor parameter names, which is confusing you - you have two xs which refer to two completely different things. Using your add decorator as an example, modify to:
def add(func):
def add_1():
return func() + 1 # you should return from the inner function
return add_1
Now hopefully it is clear that the argument to add should be a function, which is called inside add_1. Therefore you could do:
adder = add(create_x) # don't call create_x yet!
adder() # calling add_1, which calls create_x
which simplifies to:
add(create_x)() # note ordering of parentheses
Note that this could also be written:
#add
def create_x():
...
create_x()
where the syntax #add means create_x = add(create_x).
Once you've mastered simple decorators, note that your multi will not work as you expect - see e.g. python decorators with parameters for creating decorators that take arguments.
You have unnecessary (), change add(create_x()()) to add(create_x()),
and I suggest using x = int(raw_input('Give variable x a value: '))
See the following example:
def add(x):
def add_1():
#add_1 = x() + 1 # remove this line
return x+1
return add_1
def create_x():
x = input('Give variable x a value: ')
return x
b = add(create_x())
print 'answer: ', b()
localhost# python t.py
Give variable x a value: 5
answer: 6

Get inner function result without interaction of outer function in python

I want to get inner function result so i code it like
def main():
def sub():
a = 1
print a
exec main.__code__.co_consts[1]
using above code working successfully but i want to pass the argument to the sub function like...
def main():
def sub(x):
a = x + 1
return a
ans = exec main.__code__.co_consts[1]
print ans
in that problem is i don't know how to pass that x value.
that work must need to exec so that how to pass that x value with exec without interaction of main function
Maybe something like the code below, as suggested by this SO answer
def main():
def sub():
a = x + 1
print a
return a
exec(main.__code__.co_consts[1], {'x': 1} )

Categories