Back to Blog

Modules & Imports (import, from, as, custom modules, name) - Python Tutorial #17

Sandy LaneSandy Lane

Video: Modules & Imports (import, from, as, custom modules, name) - Python Tutorial #17 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Modules & Imports in Python: import, from, as, and Custom Modules

Understanding how to organize and reuse code is essential in Python programming. This tutorial covers importing entire modules, selecting specific functions, using aliases, creating your own modules, and the special __name__ == "__main__" guard to control script execution.

Code

# Import entire module
import math
print(math.sqrt(144))  # Output: 12.0

# Import specific functions from a module
from random import randint, choice
print(randint(1, 10))  # Random integer between 1 and 10

# Import with alias for convenience
import datetime as dt
now = dt.datetime.now()
print(now)

# Custom module: helpers.py
# (This code would be in a separate file named helpers.py)
def greet(name):
  return f"Hello, {name}!"

# Using the custom module in another script
from helpers import greet
print(greet("Alice"))  # Output: Hello, Alice!

# __name__ guard to allow or prevent code from running when imported
if __name__ == "__main__":
  print("Running directly")

Key Points

  • import module loads the entire module, accessed with module.name.
  • from module import name imports specific functions or variables directly.
  • import module as alias creates a shorter name for easier access.
  • Custom modules let you organize reusable code in separate files and import them.
  • The if __name__ == "__main__" guard ensures code runs only when the script is executed directly.