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.

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`.

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`.

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