Rolling the Dice

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.

Screenshot (16)



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.


Screenshot (17)



Image Courtesy : Pexels

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by

Up ↑

%d bloggers like this: