Jan-15-2024, 01:16 AM
This does assignment.
Normally when you assign a value to a variable, it looks for the variable in the local scope. If the variable does not exist, one is created.
Declaring a variable as global tells python to look for the variable in the global scope instead of local scope. If the variable does not exist, one is created in the global scope.
appending a value to a list modifies an existing object, it does not assign a list object to a variable. This code does assignment with a list and requires a global declaration.
def enter_number(x):
global numbers
numbers = [x]
dog += 1This does not:
numbers.append(x)"global" only affects assignment.
Normally when you assign a value to a variable, it looks for the variable in the local scope. If the variable does not exist, one is created.
Declaring a variable as global tells python to look for the variable in the global scope instead of local scope. If the variable does not exist, one is created in the global scope.
appending a value to a list modifies an existing object, it does not assign a list object to a variable. This code does assignment with a list and requires a global declaration.
def enter_number(x):
global numbers
numbers = [x]