Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 7 - Modules & Packages modules Python Python Basics Python Programming: From Zero to Real-World Applications

Importing Modules - import, from, as in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to import modules
  • import vs from...import
  • Aliasing with as
Terminalpython
# Full import
import math
print(math.pi)           # 3.14159...
print(math.sqrt(16))    # 4.0

# Import specific items
from math import pi, sqrt
print(pi)               # 3.14159... (no math. prefix)
print(sqrt(16))         # 4.0

# Import everything (AVOID!)
from math import *      # Pollutes namespace

# Alias
import numpy as np      # Common convention
import pandas as pd
Avoid 'from module import *'
Star imports bring everything into your namespace. This can cause name conflicts and makes it unclear where things come from. Always use specific imports.

Practical Exercise

import math and use math.pi
from math import sqrt - use without prefix
import random as rnd - use rnd.randint(1, 6)
from datetime import datetime - get current time

Key Takeaways

  • import module: use module.function().
  • from module import func: use func() directly.
  • import module as alias: shorter name (import numpy as np).
  • Avoid from module import * - pollutes namespace.
  • Standard library: math, random, datetime, os, json, csv, logging.
Previously: Module 6 covered file handling.
Today: You learned: How to import and use modules.
Next: Lesson 44 covers the standard library.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments