Standard Library Basics (Part 1)

One of Python's greatest features is "Batteries Included" — a full suite of standard libraries comes with every Python installation. This lesson covers four of the most commonly used modules: random, time, sys, and os. Even learning just the most popular functions from each will help you solve many real-world problems.


1. random — Random Numbers

PYTHON
import random

# Random float [0, 1)
print(random.random())              # 0.3745...

# Random integer [a, b] (inclusive)
print(random.randint(1, 10))        # Random integer between 1 and 10

# Random choice
fruits = ["apple", "banana", "orange", "grape"]
print(random.choice(fruits))        # Pick one randomly

# Random sample (no replacement)
print(random.sample(fruits, 2))     # Pick 2 randomly

# Shuffle order
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(cards)
print(cards)                        # Order is shuffled

Example: Lottery Program (Difficulty ⭐)

PYTHON
import random

# Lottery pool
participants = ["Alice", "Bob", "Charlie", "Diana", "Eve",
                "Frank", "Grace", "Henry"]

# 1st prize — 1 winner
first = random.choice(participants)
print(f"🎉 1st Prize: {first}")

# 2nd prize — 2 winners (excluding 1st)
remaining = [p for p in participants if p != first]
second = random.sample(remaining, 2)
print(f"🎊 2nd Prize: {' & '.join(second)}")

# 3rd prize — 3 winners
remaining = [p for p in remaining if p not in second]
third = random.sample(remaining, 3)
print(f"🎁 3rd Prize: {' & '.join(third)}")
▶ Try it Yourself

2. time — Time Handling

PYTHON
import time

# Current timestamp (seconds since 1970-01-01)
print(time.time())                  # 1758588800.123

# Pause execution (seconds)
print("Start")
time.sleep(1)                       # Pause for 1 second
print("1 second later")

# Format current time
print(time.strftime("%Y-%m-%d %H:%M:%S"))       # 2026-06-23 16:00:00

Example: Timer (Difficulty ⭐)

PYTHON
import time

def countdown(seconds):
    """Countdown timer"""
    while seconds > 0:
        print(f"\r⏱ {seconds} seconds left", end="")
        time.sleep(1)
        seconds -= 1
    print("\r⏰ Time's up!")

# Measure code execution time
start = time.time()
total = sum(range(1000000))
end = time.time()
print(f"Execution time: {end - start:.4f} seconds")
▶ Try it Yourself

3. sys — System Interaction

PYTHON
import sys

# Python version
print(sys.version)                  # 3.13.0 ...

# Command-line arguments (when running python script.py a b c)
print(sys.argv)                     # ['script.py', 'a', 'b', 'c']

# Exit the program
# sys.exit(0)                       # Normal exit

# Standard input
# line = sys.stdin.readline()       # Read one line of input

Example: Command-Line Calculator (Difficulty ⭐⭐)

PYTHON
import sys

def main():
    # Usage: python calculator.py 3 + 5
    if len(sys.argv) != 4:
        print("Usage: python calculator.py num1 operator num2")
        print("Example: python calculator.py 3 + 5")
        return

    a = float(sys.argv[1])
    op = sys.argv[2]
    b = float(sys.argv[3])

    if op == "+":
        result = a + b
    elif op == "-":
        result = a - b
    elif op == "*":
        result = a * b
    elif op == "/":
        if b == 0:
            print("Error: cannot divide by zero")
            return
        result = a / b
    else:
        print(f"Unsupported operator: {op}")
        return

    print(f"{a} {op} {b} = {result}")

if __name__ == "__main__":
    main()
▶ Try it Yourself

4. os — Operating System

PYTHON
import os

# Current working directory
print(os.getcwd())                  # D:\project

# Change directory
# os.chdir("/tmp")

# List directory contents
for item in os.listdir("."):
    print(item)

# Create directory
# os.mkdir("new_folder")

# Check paths
print(os.path.exists("test.txt"))   # True
print(os.path.isfile("test.txt"))   # True
print(os.path.isdir("data"))        # True

# Join paths
path = os.path.join("data", "files", "test.txt")
print(path)                         # data/files/test.txt

Example: Batch File Renaming (Difficulty ⭐⭐)

PYTHON
import os

def batch_rename(directory, prefix):
    """Batch rename all .txt files in a directory"""
    files = [f for f in os.listdir(directory) if f.endswith(".txt")]
    
    for i, filename in enumerate(files, 1):
        old_path = os.path.join(directory, filename)
        new_name = f"{prefix}_{i:03d}.txt"
        new_path = os.path.join(directory, new_name)
        os.rename(old_path, new_path)
        print(f"  {filename} → {new_name}")

print("Batch rename example (display only, not executed):")
print("Iterate all .txt files, rename to prefix_001.txt format")
▶ Try it Yourself

Common Use Cases


❓ FAQ

Q Is random suitable for cryptographic random numbers?
A No. random uses a PRNG (Pseudo-Random Number Generator), which is predictable. For cryptographically secure random numbers (e.g., generating passwords, tokens), use the secrets module. Q: time.sleep() blocks the entire program. How do I do a non-blocking delay? A: sleep() does block the current thread. For non-blocking delays, use multi-threading or async frameworks like asyncio. For simple scenarios, sleep() is sufficient. Q: Should I use os or pathlib? A: Python 3.4+ recommends pathlib (more object-oriented, more intuitive), but os is lower-level and more comprehensive. Use pathlib for new projects; use os for low-level system calls.

📖 Summary

  • random: randint(), choice(), sample(), shuffle() — random selection and generation
  • time: time() timestamp, sleep() pause, strftime() formatting
  • sys: argv command-line arguments, exit() program exit
  • os: File path checks, directory operations, file renaming
  • These four modules are the "starter pack" for Python's standard library, used frequently in daily development

📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that generates 10 random integers between 1 and 100, outputs them and their average.

  2. Intermediate (Difficulty ⭐⭐): Write a password generator function generate_password(length=8) that creates random passwords containing uppercase, lowercase, and digits. Hint: Use string.ascii_letters + string.digits as the character pool; use random.choice() to pick characters.

  3. Challenge (Difficulty ⭐⭐⭐): Write a "folder statistics tool." Given a directory path (passed via sys.argv), count the number of files and total size for each file type (extension). Hint: Use os.listdir() to iterate, os.path.splitext() for extension, os.path.getsize() for file size.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏