I'm attempting to loop through a function and use a variable defined in the main scope of the program, but for some reason, it's not passed into my function. This is the first time I've used functions and variable scopes in Python, I read through the Python documentation as well as some various posts on here, but couldn't seem to figure out what I did wrong.
The function will be recursive therefore I'm unable to define them in the head of the function else it will just redefine each time. I tried doing what was done in this post in my file, but it doesn't seem to work.
I have both the main + function in one file and defined the variables I wish to use as global inside the function I want to use them in.
lv1Count = 12
lv2Count = 14
lv3Count = 18
lv4Count = 4
AL = []
def opt(target):
global lv4Count
global lv3Count
global lv2Count
global lv1Count
global AL
goal = target
if (goal <= 0 & lv4Count < 0):
pass
if (goal <= 1 & lv1Count < 0):
pass
if (goal == 2 & lv2Count < 0):
pass
if (goal == 3 & lv3Count < 0):
pass
if (goal == 4 & lv4Count < 0):
pass
opt(4)
I replaced all of the if statements with pass to avoid excessive code, but essentially whenever returning something from these statements, the comparison using the counter doesn't work as it's not successfully reading the value of this variable and the functionality doesn't occur.
1 Answer 1
Your function is working correctly: this is indeed how you use global variables, even though it is usually a bad idea. (In recursion, it is most common to pass the necessary values as arguments to the function.) If you include more details about what kind of recursion you want to do, I can help with that.
In [1]: v = 1
In [2]: def test():
...: global v
...: return v
...:
In [3]: test()
Out[3]: 1
The problem is with your if statement: you are using bitwise & instead of the normal logical operator and. Since & is evaluated first in the order of operations, you are getting problems. Consider:
In [1]: bool(1 == 1 & 2 == 2)
Out[1]: False
Why? Because this is evaluated as:
In [1]: bool(1 == (1 & 2) == 2)
Out[1]: False
Which is the same as:
In [1]: bool(1 == 0 == 2)
Out[1]: False
4 Comments
& to the and keyword and that definitely appears to be the problem! Thank you so much for letting me know, I come from Java so seeing the bitwise operator when looking through documentation made me think it was the same functionality wise. Can I ask when is it appropriate to use the bitwise operator rather than the and keyword?& works the same in Java: the logical operator and is the same as && in Java. There are plenty of questions on SO that explain what bitwise operations are useful for!&& is the equivalent to Python's & . Now I know for future reference! I'll do some research on bitwise operators, thanks again for the help!Explore related questions
See similar questions with these tags.
globalis rarely a good idea, but besides that I see no reason why it is not "successfully reading the value": what do you mean by that?