What is the expected output of the following code?
num = 1
def func():
num = num + 3
print(num)
func()
print(num)
A . 4 1
B. 4 4
C. The code is erroneous.
D. 1 4
E. 1 1
Answer: C
Explanation:
Topics: def shadowing
Try it yourself:
num = 1
def func():
# num = num + 3 # UnboundLocalError: …
print(num)
func()
print(num)
print(‘———-‘)
num2 = 1
def func2():
x = num2 + 3
print(x) # 4
func2()
print(‘———-‘)
num3 = 1
def func3():
num3 = 3 # Shadows num3 from outer scope
print(num3) # 3
func3()
A variable name shadows into a function.
You can use it in an expression like in func2()
or you can assign a new value to it like in func3()
BUT you can not do both at the same time like in func()
There is going to be the new variable num
and you can not use it in an expression before its first assignment.
Latest PCEP-30-01 Dumps Valid Version with 124 Q&As
Latest And Valid Q&A | Instant Download | Once Fail, Full Refund