Nearby lessons

99 of 108

Python - Global Keyword

Detailed Tutorial Notes

  • Local Variables: The variables which are declared inside a function are called local variables. Local variables are available only for the function in which we declared it.i.e from outside of function we cannot access. Eg:
1) def f1():
2) a=10
3) print(a) # valid

4)

5) def f2():
6) print(a) #invalid

7)

8) f1()
9) f2()

10)

11) NameError: name 'a' is not defined

global keyword:

We can use global keyword for the following 2 purposes:

  • To declare global variable inside function
  • To make global variable available to the function so that we can perform required modifications Eg 1:
1) a=10
2) def f1():
3) a=777
4) print(a)

5)

6) def f2():
7) print(a)

8)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
777
10

Eg 2:

1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)

6)

7) def f2():
8) print(a)

9)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
777
777

Eg 3:

1) def f1():
2) a=10
3) print(a)

4)

5) def f2():
6) print(a)

7)

8) f1()
9) f2()

10)

11) NameError: name 'a' is not defined

Eg 4:

1) def f1():
2) global a
3) a=10
4) print(a)

5)

6) def f2():
7) print(a)

8)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
10
10

Note: If global variable and local variable having the same name then we can access

global variable inside a function as follows

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
777
10

Recursive Functions

A function that calls itself is known as Recursive Function.

Eg:

factorial(3)=3*factorial(2)

=3*2*factorial(1)

=3*2*1*factorial(0)

=3*2*1*1

=6

factorial(n)= n*factorial(n-1)

The main advantages of recursive functions are:

  • We can reduce length of the code and improves readability
  • We can solve complex problems very easily. Q. Write a Python Function to find factorial of given number with recursion. Eg:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Nonlocal Keyword