Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. What does if __name__ == "__main__" do in a Python script?

    When a file runs directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name instead. The if-check lets a file run some code only when executed as a script, not when imported.

    BeginnerQuick answer1 min read
  2. What is the difference between a module and a package in Python?

    A module is a single .py file. A package is a directory of modules, normally with an __init__.py file, that you import using dotted names like shop.billing. Packages let you organise a large project into a hierarchy.

    BeginnerQuick answer1 min read
  3. How does Python find a module when you write import?

    Python checks sys.modules for an already-loaded copy, then searches the directories in sys.path in order: the script's folder, PYTHONPATH entries, the standard library and site-packages. The first match wins, which is why a local file can shadow a library.

    IntermediateQuick answer1 min read
  4. What does "from module import *" do, and what is __all__?

    import * brings every public name of a module into your namespace, which can silently overwrite existing names. A module can control what it exports by defining __all__, a list of names. Without __all__, names starting with an underscore are skipped.

    IntermediateQuick answer1 min read
  5. What is the difference between absolute and relative imports in Python?

    An absolute import gives the full path from the project root, like from shop.billing import total. A relative import uses dots to start from the current package, like from .billing import total. Relative imports work only inside packages.

    IntermediateQuick answer1 min read
  6. What is a circular import in Python, and how do you fix it?

    A circular import happens when module A imports B while B imports A, so one of them is used before it is fully loaded, causing ImportError or AttributeError. Fix it by restructuring, moving the shared code to a third module, or importing inside the function.

    AdvancedQuick answer1 min read