The statement `global myName` will let you modify the global...
February 4, 2025 at 04:52 PM
The statement global myName
will let you modify the global variable myName
inside a function.
Here's what the code does:
- In Python, if you want to modify a global variable inside a function (rather than create a new local variable with the same name), you must explicitly declare the variable as
global
using theglobal
keyword. - Without the
global
keyword, assignment statements inside the function will create a new local variable, leaving the globalmyName
unchanged.
For example:
myName = "Alice" # global variable
def modify_name():
global myName # Declare that we are modifying the global variable
myName = "Bob" # This modifies the global variable
modify_name()
print(myName) # Output: Bob
Without the global
keyword:
myName = "Alice" # global variable
def modify_name():
myName = "Bob" # This creates a local variable instead
print(myName) # Output: Bob (local)
modify_name()
print(myName) # Output: Alice (global remains unchanged)
The global myName
statement is necessary if you want to modify the global variable myName
inside the function.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node