Python · Some intermediate topics
Modules & Imports
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — What Are Modules?
A module is a file containing Python code that you can reuse. Python comes with hundreds of built-in modules! Instead of writing everything from scratch, you `import` what you need.
import math print(math.sqrt(16)) print(math.pi)
Here we imported the `math` module. It gives us access to mathematical functions like `sqrt()` (square root) and constants like `pi`.
Exercise 2 — How import Works
When you write `import math`, Python loads the entire module. To use something from it, you write `module.function()`.
import math print(math.floor(3.7)) print(math.ceil(3.2)) print(math.pow(2, 3))
Math Functions
`math.floor()` rounds down, `math.ceil()` rounds up, `math.pow(a, b)` computes a to the power of b.
Exercise 3 — Using math
import math print(math.sqrt(25))
What is printed?
Options
• ```25```
• ```5.0```
• ```5```
• ```12.5```
Hint : `sqrt()` returns the square root. `math.sqrt()` returns a ***float***.
Exercise 4 — Import and Use
Complete the code to import `math` and calculate the square root of 49.
____ math result = math.____(49) print(result)
Options: import from sqrt pow floor
Hint : First you need to load the module, then use the square root function.
Exercise 5 — from ... import ...
If you only need one thing from a module, use `from module import something`. This way you don't need the module name prefix.
from math import sqrt, pi print(sqrt(25)) print(pi)
Without the `from` syntax, you'd have to write `math.sqrt()` and `math.pi`. With it, you can use `sqrt()` and `pi` directly.
Exercise 6 — Import Syntax
Which line correctly imports only the `randint` function from the `random` module?
Options
• ```import randint from random```
• ```from random import randint```
• ```import random.randint```
• ```random import randint```
Hint : The syntax is `from [module] import [function]`.
Exercise 7 — The random Module
The `random` module is great for games! It lets you generate random numbers, pick random elements, and more.
import random print(random.randint(1, 10)) print(random.choice(["Aquachu", "Pyrochu", "Florachu"])) print(random.random())
Key Functions
- `randint(a, b)`: random integer between a and b (inclusive) - `choice(list)`: pick a random element - `random()`: random float between 0 and 1
Exercise 8 — from ... import
Complete the code to import and use the `choice` function from `random`.
____ random import ____ team = ["Aquachu", "Pyrochu", "Florachu"] print(choice(team))
Options: from import choice random select
Hint : You want to import a specific function from a module.
Exercise 9 — Aliases with as
You can give a module a shorter name using `as`. This is called an alias. It's just a nickname!
import random as rd team = ["Aquachu", "Pyrochu", "Florachu"] print(rd.choice(team)) print(rd.randint(1, 100))
Common Aliases
Common aliases you'll see: `import random as rd`, `import datetime as dt`, `import math as m`. In data science: `import numpy as np`, `import pandas as pd`.
Exercise 10 — Using an Alias
Complete the code to use `random` with the alias `rd`.
import random ____ rd team = ["Aquachu", "Pyrochu", "Florachu"] print(rd.____(team))
Options: as = choice select pick
Hint : The keyword for aliases comes right after the module name.
Exercise 11 — Which Import?
import random print(random.choice(["Aquachu", "Pyrochu"]))
Which alternative gives the same result?
Options
• ```from random import choice; print(choice(["Aquachu", "Pyrochu"]))```
• ```import choice from random; print(choice(["Aquachu", "Pyrochu"]))```
• ```from random import *; print(random.choice(["Aquachu", "Pyrochu"]))```
• ```import random.choice; print(choice(["Aquachu", "Pyrochu"]))```
Hint : `from module import function` lets you use the function without the module prefix.
Exercise 12 — Codémon Battle Calculator
Build a battle damage calculator using modules! 1. Import `math` and `random` 2. Generate random attack power (1-50) and defense (1-30) using `random.randint()` 3. Calculate damage: `math.floor(attack / defense * 10)` 4. Generate a critical hit: `True` if `random.random() < 0.25` 5. If critical hit, double the damage 6. Print all stats
Starter code
# Import modules # Generate random stats # Calculate damage # Critical hit check # Print results
Back to the course