How to Simulate a Dice Roll and Guess the Result in Python
An introduction to the random module
Pseudocode is a useful tool.
When you want to carry out a set of operations in Python, it’s a good strategy to first write out the necessary steps in pseudocode. While pseudocode is not a programming language, it is similar to one because it helps you break down your task into instructions that can be carried out in code.
Think of pseudocode as a bridge between spoken language and code.
In English, the problem being solved is this: I want to compare the sum of two dice rolls to a guess I have made. If I guessed the sum correctly, I win. If not, I lose.
Let’s put this in pseudocode. Here’s what I want my code to do.
- Simulate the roll of a die and store the result.
- Simulate the roll of another die and store the result.
- Add the results of the two simulations.
- Input my guess.
- Compare my guess to the actual answer.
- Print out a statement declaring whether I won or lost.
While we could make this pseudocode even more technical, the steps above will hopefully give you an idea about the benefit of…