+ 1

Why does it say that free is a local variable if I declared it outside of the function?? I just want to change the value of it

https://code.sololearn.com/cPdgDF6Eku7Z/?ref=app

28th Nov 2021, 5:21 AM
Adrian DF
Adrian DF - avatar
9 ответов
+ 7
You cannot modify a global variable(for a list see below example, how we can access and modify it) in a function, but you can access it. If you want to modify you need to declare the variable free as global in your function Ex- free = 0 def func(): global free free += 2 func() print(free)# output 2 *Instead you can place the variable free inside the function, but if you want to keep the reference of free everytime you call then make it a global variable.(using global is usually a not good idea, so placing a parameter for every call would be one of your option or use a list instead to change the references of free variable for every call) ex- free = [False] def func(): if not free[0]: print('you can change me) free[0] = not free[0] #for alternating ''' if you want to make it just available once you can simply do free[0] = True ''' else: print('Now you cannot modify me') #once check you logic statement for time , it meant it wants time only under 2 or equal to it
28th Nov 2021, 6:42 AM
Prabhas Koya
+ 7
Prabhas Koya , we should be careful by saying: "You cannot modify a global variable in a function". it depends on what we are going to modify. if we modify variable 'test' inside the function, we are going to re-assign the variable by using '=' or like '+= ...'. this is not possible, but we can change this behavior by using the global keyword for test. but we can have a variable 'lst' with a list of numbers or whatever, where we can modify the elements of the list, without using global for this variable. test = 0 lst = [1,2,3] def add(num): global test test = test + num lst[1] = 99 add(7) print(test) print(lst)
28th Nov 2021, 12:14 PM
Lothar
Lothar - avatar
+ 6
Lothar variable list; generally we talk about list ,yet I gave him an example of the list , thanks for mentioning, I will add additional info ,if there might be a confusion. You mentioned we can modify a list but we cannot modify it with += inside a function ,,,
28th Nov 2021, 12:33 PM
Prabhas Koya
+ 5
Declare in the function: global free Also the logic in line 6 needs correction. time <= 2 should be time >= 2
28th Nov 2021, 6:36 AM
Brian
Brian - avatar
+ 2
How you are doing? I didn't get any error.
28th Nov 2021, 5:31 AM
A͢J
A͢J - avatar
+ 1
I didn't, and on my PC I get this error....local variable 'free' referenced before assignment 😐
28th Nov 2021, 5:42 AM
Adrian DF
Adrian DF - avatar
+ 1
Thanks guys!!
28th Nov 2021, 11:51 AM
Adrian DF
Adrian DF - avatar
0
Did you get the free pass????
28th Nov 2021, 5:38 AM
Adrian DF
Adrian DF - avatar
0
Yes
28th Nov 2021, 5:40 AM
A͢J
A͢J - avatar