Random Numbers
Games need chance: a die decides how far you move, and the cards are dealt differently every time. The module random gives your programs random numbers:
import random
print(random.randint(1, 6))
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))The output changes from run to run. One run printed:
2
4
paperand the next one:
2
2
scissorsrandom.randint(1, 6)gives a random whole number from 1 to 6, like a die. Unlikerange(), it includes both numbers: it can give 1, and it can give 6. It needs both of them, sorandom.randint(6)ends withTypeError: Random.randint() missing 1 required positional argument: 'b'.random.choice()picks a random element of a list.
How can a computer, which only calculates, give random numbers? It calculates them. From a starting number, the seed, it works out a long series of numbers that look random. Python normally picks the seed itself, without telling you, and so the numbers come out different on every run. With random.seed(), you choose the seed yourself, and the same seed always gives the same series:
import random
random.seed(42)
print(random.randint(1, 6))
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))6
1
rockRun this program as often as you like: it prints 6, 1 and rock every time. A game leaves the seed out, otherwise every game would roll the same dice. A seed is for when you need the same numbers again, for example to test a program. That's why the exercises in this lesson set one: so that they can check what your program prints.
With a seed, each result depends on all the calls before it, in their order. Here, the first randint(1, 6) gives 6 and the second one 1, but with another call before them, both would change. So in these exercises, make exactly the calls the instructions ask for, in that order.
Instructions
- 1
A board game is about to start. Below the players, roll the die: print
Dice:and a number fromrandom.randint(1, 6). With the seed 12, the output isDice: 4. Keep the linerandom.seed(12)as it is: the exercise also tries your program with other seeds. - 2
Below, pick who starts the game: print
Starts:and one of theplayers, chosen withrandom.choice(). The output should beStarts: Eva. Once it passes, put a#in front ofrandom.seed(12)and run the program a few times: now the die and the first player change from run to run, as in a real game.