How to change a global variable inside of two define's? - python

I want x to be equal to False. (Don't ask what's the purpose of the code, this is just an example.)
x = False
def first():
global x
x = True
def second():
if x == True:
x = False
#return?
first()
second()
print(x)
I have tried return, and defining x first as global

Related

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

How to access the nonlocal variable in enclosing function from inner function if inner function already has its variable with the same name Python

I need to find the way to reference variable x = "Nonlocal" from inner_function_nonlocal(). Probably, the way how I referenced the x = "Global": globals()['x'], but I need your help with that one, please!
Please note: I can NOT comment or delete x = "Local" in order to write nonlocal x instead of it.
x = "Global"
def enclosing_funcion():
x = "Nonlocal"
def inner_function_global():
x = "Local"
print(globals()['x']) # Call the global a
def inner_function_nonlocal():
x = "Local" # <- This line can NOT be commented!!!
print(_?_?_?_?_) # <- What should I specify here in order to print x which is nonlocal?
inner_function_global()
inner_function_nonlocal()
if __name__ == '__main__':
enclosing_funcion()
output should be:
Global (this is already achieved)
Nonlocal (need help to get this one)
You can add a method to get at the Nonlocal value:
x = "Global"
def enclosing_funcion():
x = "Nonlocal"
def non_local():
return x
def inner_function_global():
x = "Local"
print(globals()['x']) # Call the global a
def inner_function_nonlocal():
x = "Local" # <- This line can NOT be commented!!!
print(non_local()) # <- What should I specify here in order to print x which is nonlocal?
inner_function_global()
inner_function_nonlocal()
if __name__ == '__main__':
enclosing_funcion()
Result:
Global
Nonlocal

How to get return output from another script?

How can i get the output from another script?
My first script to run:
from test2 import *
class Test():
def todo (self):
mult()
addx()
if __name__ == '__main__':
Test().todo()
My second script named (test2.py):
def mult():
x= 2 * 4
print(x)
return x
def addx():
sum = x + 2
print("sum",sum)
Error:
NameError: name 'x' is not defined
In the function addx() you haven't declared x. I believe you want x from mult. So you can do something like this
def addx():
x = mult()
sum = x + 2
print("sum",sum)
You should use the return value of mult, to pass it to your second function addx as a parameter.
def todo (self):
x = mult()
addx(x)
I advise you to read the Python doc section about function : https://docs.python.org/fr/3/tutorial/controlflow.html#defining-functions
In test2.py, you have not defined x
def addx():
sum = x + 2
print("sum",sum)
The problem above is that the computer doesn't know what x is. You could pass it as a parameter:
def addx(x):
sum = x + 2
print("sum", sum)
and change your code to:
from test2 import *
class Test():
def todo(self):
addx(x=mult()) # whatever number you want
if __name__ == '__main__':
Test().todo()

How to loop 2 functions in 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!

How do I set a global variable via function call?

I am trying to change the value of global variable edl_loading to True in function edl_flashing ,somehow it doesn't work?can anyone help understand why does print edl_loading prints False after call to edl_flashing in which I change the value to True
def edl_flashing():
edl_loading = True
print edl_loading
def main ():
global edl_loading
edl_loading = False
print edl_loading
edl_flashing()
print edl_loading #Why this prints as False
if __name__ == '__main__':
main()
OUTPUT:-
False
True
False
You need to use the global in both of your functions - main and edl_flashing
def edl_flashing():
global edl_loading
edl_loading = True
print edl_loading
Without the global declaration in the function, the variable name is local to the function.
The above change prints out
False
True
True

Categories