Python provides a module random that helps with tasks like this. You can take a look at it in the documentation. Here are the key things we can do with it.
The randrange function generates an integer between its lower and upper argument, using the same semantics as range β so the lower bound is included, but the upper bound is excluded. All the values have an equal probability of occurring (i.e. the results are uniformly distributed).
The random() function returns a floating point number in the range [0.0, 1.0) β the square bracket means βclosed interval on the leftβ and the round parenthesis means βopen interval on the rightβ. In other words, 0.0 is possible, but all returned numbers will be strictly less than 1.0. It is usual to scale the results after calling this method, to get them into a range suitable for your application.
In the case shown here, weβve converted the result of the method call to a number in the range [0.0, 5.0). Once more, these are uniformly distributed numbers β numbers close to 0 are just as likely to occur as numbers close to 0.5, or numbers close to 1.0. If you continue to press the run button you will see random values between 0.0 and up to but not including 5.0.
It is important to note that random number generators are based on a deterministic algorithm β repeatable and predictable. So theyβre called pseudo-random generators β they are not genuinely random. They start with a seed value. Each time you ask for another random number, youβll get one based on the current seed attribute, and the state of the seed (which is one of the attributes of the generator) will be updated. The good news is that each time you run your program, the seed value is likely to be different meaning that even though the random numbers are being created algorithmically, you will likely get random behavior each time you execute.
While you might want to use the math module for other numerical computations in your program, it does not contain functions that are likely to help you simulate a dice roll.
Computers generate random numbers using a deterministic algorithm. This means that if anyone ever found out the algorithm they could accurately predict the next value to be generated and would always win the lottery.
They would just generate the same numbers over and over again.