Line At A Time
Lesson 25: Roll a Six
Roll a Six Grand finale: keep rolling a dice until you get a 6.
1import random
2
3def roll_dice():
4 return random.randint(1, 6)
5
6roll = roll_dice()
7while roll != 6:
8 print(roll)
9 roll = roll_dice()
10print("You rolled a 6!")
Terminal
$ python3 main.py
(prints a random number, different every run)
Every line, explained
import random
import loads one of Python's built-in toolboxes at the top of the file. The random toolbox is full of tools for making random numbers.
def roll_dice():
def defines a function: your own named block of code. The name is followed by round brackets and a colon, and the body is indented. Defining a function does nothing on its own: it waits until somebody calls it. In Python you must define a function before the line that calls it. Our function rolls one six-sided dice.
return random.randint(1, 6)
random.randint(1, 6) hands back a random whole number from 1 to 6, both ends included. Run the program again and you will (probably) get different numbers! return hands the number back to whoever called the function; calling roll_dice() is like rolling a real dice and reading off the result.
roll = roll_dice()
Calls roll_dice and stores the number it returns. This is our first roll.
while roll != 6:
A while loop repeats its indented body for as long as the condition is True. The condition is checked again before every trip around the loop. != means "not equal": keep looping while the roll is NOT a 6.
print(roll)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Shows each roll that wasn't a 6.
roll = roll_dice()
Rolls again, replacing the old number. Then the loop checks the condition again.
print("You rolled a 6!")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Outside the loop, so it runs once, the moment a 6 finally appears. You wrote a program that uses variables, a function, return, a loop and randomness. That is real programming!