Vortex
Vortex

Reputation: 23

Why is a variable able to be defined after definition of function using it?

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.

Upvotes: 2

Views: 130

Answers (3)

John Y
John Y

Reputation: 14519

In Python, variables are created when you assign them. In your case, student_list is 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 global statement is, since global variables are already visible inside functions: global allows you to reassign a global variable, and have it take effect globally. For example:

def b():
    global a
    a = 5

a = 4
print(a)  # prints 4
b()
print(a)  # prints 5

In most cases, you don't need the global statement, 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 use global very much, though.)

Upvotes: 1

Laur Ivan
Laur Ivan

Reputation: 4177

The way I understand it is that your program has 3 parts

  1. define print_list()
  2. initialise student_list (global variable)
  3. call print_list()

When you call print_list(), student_list is already there. Also, in a function you have the scopes where a variable (student_list) is searched: 1. local scope (it'll fail because you don't have it defined, only referred) 2. global scope (it'll succeed, because it was just initialised

Upvotes: 1

wim
wim

Reputation: 362577

By the time you're calling print_list(), you have student_list defined as a global variable.

Upvotes: 6

Related Questions