+ 1
global keyword in python
def func(): global a,b a+=2 b+=5 c.append(3) print(a,b,c) a,b,c=10,15,[] func() In the above code i didn't mention that I was gonna use the c variable inside the function but it is still able to modify the values of c variable, how is that possible. But if I use the variables a or b without mentioning the global keyword inside the function it shows an error so I'm just confused about that.Is it because of list data type or what is the mechanism behind the code. https://code.sololearn.com/c4oMaOGipSid/?ref=app
1 Réponse
+ 4
The variables are defined outside of a function, making them globally accessible. If they were declared inside the function they would only be locally accessible.
To modify the 'a,b' variables 'Global' is needed inside the function because their values are being modified. lists do not require the 'Global' declaration inside the function.
https://www.google.com/amp/s/www.geeksforgeeks.org/global-local-variables-JUMP_LINK__&&__python__&&__JUMP_LINK/amp/