Python Tutorial: Variable Scope - Understanding the LEGB rule and global/nonlocal statements

Corey Schafer · 414K views · 2016 · 20:59

Open on YouTube

Python, Ruby & scripting languagesEducation & learningtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when asking or answering questions about why a variable assignment inside a function or exec string does not affect the outer value, or when global and nonlocal come into play.

Recommended by 2 people across 2 different months, 2020 to 2021.

What it is

A 21-minute Python tutorial by Corey Schafer on variable scope. It explains the LEGB rule (local, enclosing, global, built-in) and shows how the global and nonlocal statements change where a variable can be read or assigned.

What people said

Recommends Anthony1223 · 2021-11 · Stack Overflow · on “why can't I declare a global variable inside an "exec" string”

Okay, I think I understand a bit more. It's actually your ostr='asd' that's throwing the error off since python thinks it's a local variable I suggest watching this to understand more [this video] as for a fix I'd suggest re-assigning ostr to another variable if you want to modify it in the local scope, but you will have to declare it as a global variable to modify it in the global scope. Hope that helps

Recommends Mohammad Reza Karimi · 2021-12 · Stack Overflow · on “How to change value of variable passed as an argument in python?”

Let me introduce it with your example: def invert(b): b = not b myVar = False invert(myVar) print(myVar) What is actually happening here? Any value that you pass to the "invert" function as a parameter will be a new variable inside it and has its own memory address. So in this case, you can do something like this: def invert(b): return not b myVar = False print("My var before inverting:", myVar) myVar = invert(myVar) # line 6 print("My var after inverting:", myVar) Can you see the changes? We are returning a value from the invert function and reassigning the myVar variable with it. I suggest you read more about scopes or watch this tutorial. [this video]

Cites Kieran Wood · 2020-05 · Stack Overflow · on “Invalid syntax using += operator”

Three things with this code: the rnum assignment will fail because you are not doing integer division You actually want global not non-local in this case. Though you should avoid using global variables like this. You can do the second line as part of the first This would be what I think you want: from random import randint as rd citizens = rd(10000, 1000000) def function(): global citizens # Tells python you want the global value rnum = rd(1,citizens//2) # Uses the global value since python knows to do that citizens -= rnum Though I would recommend avoiding nonlocal altogether since it can cause many bugs down the road. I would suggest doing something like this stylistically: from random imp