May 2019
Beginner
528 pages
29h 51m
English
We now take a brief diversion into a popular type of programming application—simulation and game playing. You can introduce the element of chance via the Python Standard Library’s random module.
Let’s produce 10 random integers in the range 1–6 to simulate rolling a six-sided die:
In [1]: import randomIn [2]: for roll in range(10):...: print(random.randrange(1, 7), end=' ')...:4 2 5 5 4 6 4 6 1 5
First, we import random so we can use the module’s capabilities. The
randrange function generates an integer from the first argument value up to, but not including, the second argument value. Let’s use the up arrow key to recall the for statement, then press Enter to re-execute it. Notice ...
Read now
Unlock full access