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

Python · Basic · question 9 of 100

What is a module in Python, and how do you import a module?

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

In Python, a module is a file that contains Python code. A module can define functions, classes, and variables that can be used in other Python programs. Modules are an important part of the Python ecosystem, as they allow you to reuse code that has already been written and tested.

To use a module in Python, you first need to import it into your program. There are several ways to import a module in Python:

import statement: The import statement is used to import a module into your program. Here is an example:

    import math
    
    result = math.sqrt(4)
    print(result) # Output: 2.0

In this example, we import the math module using the import statement. We can then use the functions and variables defined in the math module by prefixing them with the module name, like math.sqrt().

from ... import statement: The from ... import statement is used to import specific functions, classes, or variables from a module. Here is an example:

    from math import sqrt
    
    result = sqrt(4)
    print(result) # Output: 2.0

In this example, we import the sqrt function from the math module using the from ... import statement. We can then use the sqrt() function directly, without prefixing it with the module name.

import ... as statement: The import ... as statement is used to import a module and give it a different name. Here is an example:

    import math as m
    
    result = m.sqrt(4)
    print(result) # Output: 2.0

In this example, we import the math module and give it the name m using the import ... as statement. We can then use the functions and variables defined in the math module by prefixing them with the name m, like m.sqrt().

It’s important to note that Python comes with a standard library of modules that are included with the language, and you can also install third-party modules using tools like pip. By using modules in Python, you can save time and write more efficient, reusable code.

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