I have a very simple and maybe dumb question:
Why does this work?
def print_list():
for student in student_list:
print(student)
student_list = ["Simon", "Mal", "River", "Zoe", "Jane", "Kaylee", "Hoban"]
print_list()
The way I’ve come to know functions and arguments, the function print_list() shouldn’t recognize student_list since I didn’t assign it as an argument for the function.
In Python, variables are created when you assign them. In your case,
student_listis assigned in the global scope, so it is a global variable. (The global scope is the stuff that isn’t inside your function.)When Python encounters a variable inside a function that is not a local variable (that is, it was not passed in as an argument and was not assigned inside the function), it automatically looks for the variable in the global scope.
If you are wondering what the purpose of the
globalstatement is, since global variables are already visible inside functions:globalallows you to reassign a global variable, and have it take effect globally. For example:In most cases, you don’t need the
globalstatement, and I would recommend that you don’t use it, especially until you are much more experienced in Python. (Even experienced Python programmers tend not to useglobalvery much, though.)