Quiz 2

Modules & Importing Libraries

1614 words
8 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Modules & Importing Libraries > **Why read this?** Python alone gives you the basics. But its real power is the vast ecosystem of libraries — pre-written code that handles everything from advanced math to generating random numbers.

Modules & Importing Libraries

Why read this? Python alone gives you the basics. But its real power is the vast ecosystem of libraries — pre-written code that handles everything from advanced math to generating random numbers. Modules are how you tap into that power.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Import modules using import, from...import, and import...as
  2. Use functions from the math module (sqrt, ceil, floor, sin, cos, etc.)
  3. Use functions from the random module (randint, choice, shuffle)
  4. Understand the difference between absolute and relative imports
  5. Write portable import statements following Python conventions

📋 Prerequisites

  • All Week 1-2 topics. Variables, functions, conditionals — all needed here.

📖 Core Content

8.1 What Problem Do Modules Solve?

Intuition: Imagine building a house but having to make every nail, every brick, every pipe from scratch. That's programming without modules. Modules are like prefabricated parts — someone else did the hard work, and you just plug them in.

8.2 Three Ways to Import

Method 1: import module — imports the whole module, use module.function()
python
import math
print(math.sqrt(25))    # 5.0
print(math.pi)           # 3.141592653589793
Method 2: from module import name — imports specific items, use directly
python
from math import sqrt, pi
print(sqrt(25))          # 5.0 (no need for math.sqrt)
print(pi)                # 3.141592653589793
Method 3: import module as alias — import with a nickname
python
import math as m
print(m.sqrt(25))        # 5.0 (using alias)
Diagram Rendering diagram

8.3 The math Module

python
# runnable
import math
# Constants
print("pi:", math.pi)
print("e:", math.e)
# Rounding
print("ceil(4.2):", math.ceil(4.2))    # 5 (ceiling — round UP)
print("floor(4.9):", math.floor(4.9))  # 4 (floor — round DOWN)
# Powers and roots
print("sqrt(144):", math.sqrt(144))    # 12.0
print("pow(2, 10):", math.pow(2, 10))  # 1024.0
# Trigonometry (angles in radians)
print("sin(pi/2):", math.sin(math.pi/2))  # 1.0
print("cos(0):", math.cos(0))             # 1.0
# Log and exp
print("log(100, 10):", math.log(100, 10)) # 2.0 (log base 10)
print("log(e):", math.log(math.e))        # 1.0 (natural log)
Output:
pseudo
pi: 3.141592653589793
e: 2.718281828459045
ceil(4.2): 5
floor(4.9): 4
sqrt(144): 12.0
pow(2, 10): 1024.0
sin(pi/2): 1.0
cos(0): 1.0
log(100, 10): 2.0
log(e): 1.0

8.4 The random Module

python
# runnable
import random
# Random integer between a and b (INCLUSIVE)
dice = random.randint(1, 6)
print("Dice roll:", dice)
# Random float between 0 and 1
print("Random float:", random.random())
# Random choice from a list
fruits = ["apple", "banana", "cherry", "date"]
print("Random fruit:", random.choice(fruits))
# Shuffle a list (modifies in-place)
cards = ["Ace", "King", "Queen", "Jack"]
random.shuffle(cards)
print("Shuffled cards:", cards)
# Random float between a and b
print("Uniform(10, 20):", random.uniform(10, 20))
Output (varies each run):
pseudo
Dice roll: 4
Random float: 0.7432918374091287
Random fruit: cherry
Shuffled cards: ['Queen', 'Ace', 'Jack', 'King']
Uniform(10, 20): 15.278345190187345

8.5 Worked Example 1: The Birthday Paradox

What's the probability that in a group of 23 people, at least two share a birthday?
python
# runnable
import random
def has_duplicate_birthday(group_size):
    """Return True if at least two people share a birthday."""
    birthdays = []
    for _ in range(group_size):
        bday = random.randint(1, 365)
        if bday in birthdays:
            return True
        birthdays.append(bday)
    return False
# Run simulation 10000 times
trials = 10000
group_size = 23
count = 0
for _ in range(trials):
    if has_duplicate_birthday(group_size):
        count += 1
probability = count / trials * 100
print(f"With {group_size} people, shared birthday probability: {probability:.1f}%")
Output (approximate):
pseudo
With 23 people, shared birthday probability: 50.7%

8.6 Worked Example 2: Guessing Game

python
# runnable
import random
secret = random.randint(1, 100)
attempts = 0
print("I'm thinking of a number between 1 and 100.")
while True:
    guess = int(input("Your guess: "))
    attempts += 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"Correct! You got it in {attempts} attempts.")
        break

8.7 Worked Example 3: GCD and LCM

python
# runnable
import math
a = int(input("First number: "))
b = int(input("Second number: "))
gcd = math.gcd(a, b)
lcm = abs(a * b) // gcd
print(f"GCD({a}, {b}) = {gcd}")
print(f"LCM({a}, {b}) = {lcm}")

8.8 Worked Example 4: Password Generator

python
# runnable
import random
import string
length = int(input("Password length: "))
# Combine all character types
chars = string.ascii_letters + string.digits + "!@#$%^&*"
password = ""
for _ in range(length):
    password += random.choice(chars)
print(f"Generated password: {password}")

8.9 Worked Example 5: Scientific Calculator

python
# runnable
import math
print("Scientific Calculator")
print("1. Square root")
print("2. Sine (degrees)")
print("3. Cosine (degrees)")
print("4. Logarithm (base 10)")
choice = int(input("Choose (1-4): "))
value = float(input("Enter value: "))
if choice == 1:
    if value >= 0:
        print(f"√{value} = {math.sqrt(value):.4f}")
    else:
        print("Cannot compute sqrt of negative number")
elif choice == 2:
    rad = math.radians(value)
    print(f"sin({value}°) = {math.sin(rad):.4f}")
elif choice == 3:
    rad = math.radians(value)
    print(f"cos({value}°) = {math.cos(rad):.4f}")
elif choice == 4:
    if value > 0:
        print(f"log({value}) = {math.log10(value):.4f}")
    else:
        print("Cannot compute log of non-positive number")

📐 Key Concepts Reference

Import StyleSyntaxUsageWhen to Use
Full moduleimport mathmath.sqrt(9)Use module many times, avoid name conflicts
Specific namesfrom math import sqrtsqrt(9)Use a few functions, clear context
Aliasimport numpy as npnp.array([1,2])Long module names, standard aliases
All namesfrom math import *Avoid!Pollutes namespace, unclear origins
Key math Functions:
FunctionDescriptionExampleResult
sqrt(x)Square rootmath.sqrt(144)12.0
ceil(x)Round upmath.ceil(4.2)5
floor(x)Round downmath.floor(4.9)4
pow(x, y)x to power ymath.pow(2, 10)1024.0
sin(x)Sine (x in radians)math.sin(math.pi/2)1.0
cos(x)Cosine (x in radians)math.cos(0)1.0
log(x, base)Logarithmmath.log(100, 10)2.0
gcd(a, b)Greatest common divisormath.gcd(12, 18)6
Key random Functions:
FunctionDescriptionExampleResult
randint(a, b)Random int a to b inclusiverandom.randint(1, 6)Random 1-6
random()Random float 0 to 1random.random()e.g., 0.374
choice(seq)Random elementrandom.choice(["a","b"])Random element
shuffle(lst)Shuffle list in-placerandom.shuffle(cards)None (modifies list)
uniform(a, b)Random float a to brandom.uniform(0, 10)e.g., 5.27

⚠️ Common Pitfalls

Pitfall 1: Name Conflicts with from import

The mistake: from math import * then later defining your own sqrt function. Why: Your sqrt silently overrides math's sqrt. Or worse — you overwrite a Python built-in. Fix: Use import math (full module) or import only what you need: from math import sqrt.

Pitfall 2: Shadowing Standard Modules

The mistake: Naming your file random.py, then import random imports YOUR file, not the standard library. Fix: Never name your files after standard library modules.

Pitfall 3: Forgetting math. Prefix

The mistake: sqrt(25) after import math (without math. prefix). The error: NameError: name 'sqrt' is not defined Fix: Use math.sqrt(25) or do from math import sqrt.

Pitfall 4: random.randint Upper Bound

The mistake: random.randint(0, 10) thinking it returns 1-9. Truth: randint(a, b) includes BOTH endpoints. So randint(1, 6) can return 6. Fix: Use randrange(0, 10) for exclusive upper bound, or remember randint is inclusive.

📝 Practice Questions

Q1: What does math.ceil(-3.7) return?
Answer: -3
ceil() rounds UP (toward positive infinity). -3.7 rounded up is -3 (because -3 > -3.7). Q2: What's the output?
python
import math
print(math.floor(3.999))
Answer: 3
floor() rounds DOWN (toward negative infinity). 3.999 floored is 3. Q3: Fix this code:
python
import random
print(randint(1, 10))
Answer: Error: NameError: name 'randint' is not defined Fix: Either print(random.randint(1, 10)) or from random import randint. Q4: Write code to simulate rolling two dice and printing their sum.
Answer:
python
# runnable
import random
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
print(f"Dice: {die1} + {die2} = {die1 + die2}")
Q5: What's the output?
python
from math import pi, sqrt
print(sqrt(pi))
Answer:
pseudo
1.772453850905516
sqrt(pi) = √3.14159... ≈ 1.772 Q6: Write code using math.gcd to find if two numbers are coprime (GCD = 1).
Answer:
python
# runnable
import math
a, b = 15, 28
if math.gcd(a, b) == 1:
    print(f"{a} and {b} are coprime")
else:
    print(f"{a} and {b} are not coprime")
Q7: What does random.shuffle() return?
Answer: None
shuffle() modifies the list IN PLACE and returns None. It does NOT create a new list. If you do new_list = random.shuffle(my_list), new_list will be None. Q8: Write a program that picks a random card from a standard 52-card deck.
Answer:
python
# runnable
import random
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

suit = random.choice(suits)
rank = random.choice(ranks)
print(f"{rank} of {suit}")
*Q9: What's the difference between import math and from math import ?
Answer:
  • import math loads math into a namespace. You access functions via math.sqrt(25).
  • from math import * loads ALL math names directly into your namespace. You can use sqrt(25) directly, but it may override your existing variables/functions.
Use import math unless you have a good reason not to. Q10: Write a program that calculates the distance between two points (x1,y1) and (x2,y2) using math.hypot or math.sqrt.
Answer:
python
# runnable
import math
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"Distance: {distance}")  # 5.0
# Or: distance = math.hypot(x2-x1, y2-y1)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.