Python lesson 19

Import and Random. Borrowing Superpowers

Python comes with toolboxes. Import opens one.

Somebody Already Wrote It

You do not have to build everything yourself. Python ships with modules. Ready-made toolboxes of code. Import brings one into your program, and then you use its tools with a dot.

import random

random.randint(1, 6) # a whole number, 1 to 6
random.choice(["a", "b"]) # one item from a list

import random

dice = random.randint(1, 6)
print("You rolled", dice)

Open the Toolbox

Roll the Dice

Run this a few times. The number changes. That is the point.

import random

for roll in range(5):
    print("Roll", roll + 1, ":", random.randint(1, 6))

The Maths Toolbox Too

random is not the only one. Math holds things like pi and square roots. Every module works the same way: import it, then reach for its tools with a dot.

import math

math.pi # 3.14159...
math.sqrt(16) # 4.0
math.floor(2.7) # 2

import math

print("Pi is about", round(math.pi, 2))
print("The square root of 81 is", math.sqrt(81))
print("2.7 rounded down is", math.floor(2.7))

A Magic 8-Ball

Pick a random answer from the list. Add your own answers and run it again.

import random

answers = ["Definitely", "Ask again later", "No way", "It is certain"]
print("The 8-ball says:", random.choice(answers))

Two Dice, One Total

Roll two dice, print each one, then print the total.

import random

first = random.randint(1, 6)
second = random.randint(1, 6)
print("First:", first)
print("Second:", second)
print("Total:", first + second)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.