Modules & import, explained simply
Python comes with a huge toolbox of extra code grouped into modules. Instead of writing everything yourself, you import a module and use its tools.
After import math you can use math.sqrt() for square roots, math.ceil() to round up and math.floor() to round down. The dot means "the tool called this, inside that module".
The random module is a favourite for games: random.randint(1, 6) rolls a dice, and random.choice() picks from a list.
Example: How many buses?
import math
children = 45
seats_per_bus = 20
buses = math.ceil(children / seats_per_bus)
print(f"We need {buses} buses.")Output
We need 3 buses.45 ÷ 20 is 2.25, but you cannot book a quarter of a bus, so math.ceil rounds up.
Try this
- Use random.randint to roll a dice five times.
- Try math.floor on the same sum and explain why it would be the wrong choice here.
- Pick a random joke from a list with random.choice.
