Programs · Program 7-14
Q.Program 7-14: Program to access any variable outside the function
Uttarakhand UbseTextbookSubjective· 2mImportance★★★★★est
40% · 16/40 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Program 7-14 shows that a function can read a variable defined outside it: num is global, the function body references it without declaring anything, and both prints show 5.
The idea — variable scope. Names in Python are resolved by the LEGB rule: Local → Enclosing → Global → Built-in. When someFunc() refers to num and has no local num of its own, Python finds the global num and uses its value. No global keyword is needed for mere reading.
# Program 7-14: accessing a variable defined outside the function
def someFunc():
print("Inside the function, num =", num) # no local num -> global is read
num = 5 # global variable
someFunc()
print("Outside the function, num =", num)
Expected output
Inside the function, num = 5
Outside the function, num = 5
Reading the run
num = 5creates a global variable (note it is assigned before the call, which is all that matters — thedefearlier in the file is fine). …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.