Python 3 — Modules, Libraries & standard imports
You don't need to write every feature from scratch. Python comes with a massive "Standard Library" of built-in code blocks (modules) that handle math calculations, random generators, date logic, and web integrations. Let's see how to use them.
To use code from a module, you must import it at the top of your program. Here is how we import and use the standard math and random modules:
import math
import random
# Using math functions
square_root = math.sqrt(64)
print(f"Square Root: {square_root}") # 8.0
# Generating a random number between 1 and 10
lucky_number = random.randint(1, 10)
print(f"Lucky Number: {lucky_number}")
If you only need a single function from a large module, you can import it specifically using the from ... import syntax. This allows you to call the function directly without prepending the module name:
from datetime import datetime
# Fetching current timestamp
now = datetime.now()
print(f"Current Date/Time: {now}")
If Python's standard library doesn't cover your needs, you can import libraries written by other developers. In your local terminal, you can download packages from the Python Package Index (PyPI) using pip:
# Running in local command terminal:
pip install requests
Once installed, you can import it like standard modules: import requests.
Never name your script file the same name as a Python standard library module (like naming your file math.py). If you do, Python will import your script instead of the standard math module, causing standard math methods to fail with errors!
Import the 'random' module, create a list of three strings representing prizes (e.g. "Car", "Bike", "Candy"), and use 'random.choice(prizes)' to print out a random prize winner.