Most asked top Interview Questions and Answers | Online Test | Mock Test
Education platform for interview prep, online tests, tutorials, and live practice

Build skills with focused learning paths, mock tests, and interview-ready content.

WithoutBook brings subject-wise interview questions, online practice tests, tutorials, and comparison guides into one responsive learning workspace.

Search the library
Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: How do you set a global variable in a function in Python?
Answer:

x = 1 # make a global
def f():
  print x # try to print the global
  for j in range(100):
    if q>3:
      x=4

 
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently, the print x attempts to print an uninitialized local variable and will trigger a NameError.


The solution is to insert an explicit global declaration at the start of the function:

 
def f():
  global x
  print x # try to print the global
  for j in range(100):
    if q>3:
      x=4

 
In this case, all references to x are interpreted as references to the x from the module namespace.

Save For Revision

Bookmark this item, mark it difficult, or place it in a revision set.

Open My Learning Library
Is it helpful? Yes No

Most helpful rated by users:

©2026 WithoutBook