We all have played dice games when we were kids. The unique thing about a dice is that it gives a random number from 1 to 6 without favoring any number.

How can you make a machine that can generate random numbers?

Can a program be written to iterate from 1 to 6 and randomly select numbers? This is not easy.

Python makes this easy for us using the random module. The random module contains functions to output random numbers. The functions under random module are available in this link Random module.

Let us write a dice rolling program in Python.

We will be using the function called random.randint(a,b) which returns a random integer N such that a<= N <= b.

Here we import 2 built in modules called sys and random. We initialize a while loop which is infinite (while True loop).Inside the while loop, we ask for the user’s input. We use such an infinite loop because the game requires you to keep rolling the dice continuously for each player until the game ends. If the user’s input is y or Y ,we call the random.randint function and print a number from 1 to 6. If the user enters anything else we exit from the program using sys.exit( ) which is a way to terminate a Python script. This is the reason why we imported the sys module.

Let us look at a few outputs.

Image Courtesy : Pexels