GPYC practice question 1 of 15

What will the contents of the "__name__" variable be if the program "gpyc.py" is run as a standalone program?

Full set: 75 questions
Answer options
A: The name of the Python version used to create the module
B: __main__ Correct answer
C: The name of the GCC compiler used to compile the module
D: gpyc
Correct Answer:
B. __main__
Explanation

In Python, name is a special built-in variable that is automatically set for every module. Its value depends on how the module's code is being used. When the Python interpreter executes a script directly (i.e., as a standalone program), it sets the name variable for that script's scope to the string 'main'. This behavior is fundamental for creating reusable modules, as it allows a script to contain code that only runs when it is executed directly, by checking if name == 'main':, but not when it is imported by another module.

Why Incorrect

A. The name variable does not store Python version information; that is typically accessed through the sys or platform modules.
C. name is a feature of the Python runtime environment and is unrelated to the C compiler (like GCC) used to build the CPython interpreter.
D. The value of name would be 'gpyc' only if the file gpyc.py were imported as a module into another script, not when run directly. ---

References

1. Official Python Documentation, The Python Tutorial: In the section on modules, it states: "A module’s name is set to 'main' when it is read from standard input, a script, or from an interactive prompt."

Source: The Python Software Foundation, "The Python 3 Tutorial," Section 6. Modules. Available at: https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts

2. Official Python Documentation, The Python Language Reference: The execution model for top-level scripts is defined here. "The main module is the module where execution of the program starts. [...] its name is initialized to 'main'."

Source: The Python Software Foundation, "The Python Language Reference," Section 3.4.1. The main module. Available at: https://docs.python.org/3/reference/import.html#the-main-module

3. MIT OpenCourseWare, Introduction to Computer Science and Programming in Python: Course materials explain this concept as a standard convention. "When you run a file, the name variable is set to 'main'. When you import a file, the name variable is set to the name of that file."

Source: MIT OpenCourseWare, 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016, Lecture 5 Notes, Section "Using if name == 'main'". Available at: https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/pages/lecture-slides-and-files/ (See MIT60001F16Lec5.pdf)

Scroll to Top