Scope

Scope of a variable is its lifetime in the program.

The region of the program in which it can be accessed.

Function Scope

The scope of a variable inside a function is only limited to the function itself.

Accessing such variable outside of the function results in an exception.

Let's look at the following example:

If we uncomment line 6 of the code, it will result in exception.

Let's see another example with a function:

Output:

If we uncomment line 4 an exception will be thrown because there is no num variable defined in the function yet.

At line 5 a value is set to the num variable.

This doesn't change the value of the num variable defined at line 1.

Scope of if statements

Unlike functions if statements don't limit variables scope.

Let's look at the following example:

Output:

age variable is defined at line 2.

It can be accessed at any line afterwards despite the indentation.

If at line 1 True is replaced wtih False, then line 5 will throw exception.

Global variables

Global variables can be accessed in any scope.

Global variables are defined using the global keyword.

Let's compare global and local variables:

Output:

A global variable named my_global_var is defined at line 2.

A local variable named local_var is defined at line 3.

We can access the global variable outside of the function it was defined in at line 9.

If line 10 is uncommented, it will result in exception due to accessing local variable outside of the function it is defined in.