WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Intermediate · question 30 of 100

What is the purpose of the ’name’ variable in Python?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

In Python, the __name__ variable is a special built-in variable that is used to determine whether a module is being run as the main program or being imported as a module into another program. The value of __name__ changes depending on how the module is being used.

When a module is run as the main program, the value of __name__ is set to ’__main__’. This allows the module to perform certain actions only when it is run directly, rather than being imported into another program. For example, you might want to include some test code or debugging statements in a module, but only have them run when the module is run as the main program:

    def add_numbers(x, y):
        return x + y
    
    if __name__ == '__main__':
        result = add_numbers(2, 3)
        print(result)

In this example, the add_numbers function is defined, but the print statement is only executed when the module is run as the main program. If the module is imported into another program, the print statement is not executed.

When a module is imported into another program, the value of __name__ is set to the name of the module, without the .py extension. This allows the module to be used as a library by other programs, without running any code that should only be executed when the module is run as the main program.

In summary, the __name__ variable in Python is a special built-in variable that is used to determine whether a module is being run as the main program or being imported as a module into another program. The value of __name__ changes depending on how the module is being used, and can be used to include certain actions only when the module is run directly.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics