Variable Scope

Scope is the visibility/availability of the variable to use.

When you define a variable in function, it can be available inside that function only and it won’t be available to use outside of that function.

When you define a variable inside the program as global variable, it will be available to use anywhere in the program.

Example:

def get_name():
    name = “Tom”
    print(“Player name is: ”+ name) 	## Player name is: Tom

In the above example, the name variable visible inside get_score() function only.

Example:

def get_name():
    print(“Player name is:”+name) 		## Player name is: Tom
name=”Tom”

In the above example, the name variable visible in program level. It can be available to use anywhere in the program.

Example:

def get_name():
    name = “Tom”
print(“Player name is:”+ name)      # Throws NameError message

In the above example, name variable defined inside the get_name() function and it is visible only inside that function. So, the above program throws the error message since you are accessing from outside of the function.



Related Tutorials