Summary
In this lesson, you learned that:
- A module is a file of Python code with functions and values for one subject. Python comes with many of them, its standard library.
import mathat the top of the program imports a module, and you reach what's in it with a dot:math.sqrt(16),math.pi. Without the import, the program ends withNameError: name 'math' is not defined. Did you forget to import 'math'?; a typo in the module's name gives aModuleNotFoundError.from math import sqrt, piimports only the names you list, and you write them without the module's name:sqrt(81). The namemathitself isn't imported then.- A program of several files imports its own files the same way:
import shopfor the fileshop.py. round(x)rounds to a whole number andround(x, 2)to two decimal places. It's built in, so it needs no import. A number exactly halfway goes to the even one:round(2.5)is2.math.ceil()rounds up andmath.floor()rounds down, for example to work out how many buses you need for everyone.random.randint(1, 6)gives a random whole number from 1 to 6, both included, andrandom.choice(players)a random element of a list.random.seed(42)makes a program get the same random numbers on every run, as long as it makes the same calls in the same order. A game leaves it out; a test uses it.statistics.mean()gives the average of a list andstatistics.median()the value in the middle, which one extreme value doesn't move.
In the next lesson, Classes and Objects, you'll learn to make your own kinds of values, such as a pet with its own name and its own methods.
Instructions
- 1
Let's practice with dice. Write a function
roll_dice(count)that rolls a diecounttimes and returns the rolls as a list. Each roll israndom.randint(1, 6). Printroll_dice(10): with the seed 3, it's[2, 5, 5, 2, 3, 5, 4, 6, 5, 1]. Keep the linerandom.seed(3): the exercise also tries other seeds. - 2
Below, roll 1000 dice with
roll_dice(1000)and print their average withstatistics.mean(), rounded to two decimal places:Average: 3.51. The more dice you roll, the closer their average gets to3.5, the average of 1, 2, 3, 4, 5 and 6.