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 pdAvoid '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.
Comments
Comments
Post a Comment