Q3. Output of the following Python Code

What is the output of the following Python Code?

num1 = 10

def update():
    num1 = 20
    print("num1 inside update =", num1)
      
update()

Options:

1.

UnboundLocalError: local variable 'num1' referenced before assignment

2.

num1 inside update = 10

3.

num1 inside update = 20

4.

num1 inside update = 30

Answer: 3

num1 inside update = 20

This is because num1 which is inside the update() method is a brand new variable. It is not related to the global num1. Here is the tutorial on global and local variables in Python.

Leave a Comment