English

Predict the output of the given code snippet. ptr=40 def result(): print ptr ptr=90 def func(var): if var<=60: ptr=30 print ptr result() func(60) func(70)

Advertisements
Advertisements

Question

Predict the output of the given code snippet.

ptr=40
def result():
     print ptr
     ptr=90
def func(var):
     if var<=60:
     ptr=30
     print ptr
result()
func(60)
func(70)
Short Answer
Advertisements

Solution

Trace:

  • Inside result(), the statement ptr = 90 makes ptr a local variable throughout that function.
  • Therefore, print(ptr) tries to use the local ptr before it has been assigned a value.
  • The program stops at result(); neither func(60) nor func(70) executes.
UnboundLocalError: cannot access local variable 'ptr' where it is not associated with a value

To modify the global ptr, write global ptr inside result() before assigning to it.

shaalaa.com
  Is there an error in this question or solution?
Chapter 3: Classes in Python - EXERCISE [Page 62]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 3 Classes in Python
EXERCISE | Q 14. (i) | Page 62
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×