Simple Dice Rolling Simulator using Python

In this post, we will write a simple python program to simulate rolling dice.

Python is the best when it comes to writing short and functional code. We can write this text-based simulator in under 20 lines. Before diving in, here are the prerequisites to understand this code.

  1. Familiarity with the syntax of python language. You do not need to be a pro, to understand this code.
  2. Most importantly, curiosity to learn.

Writing the Code

  • Let’s start by importing the random module of python, it helps us to select a random number from a list or a sequence in general. If you are interested to learn more about the random module, click on https://docs.python.org/3/library/random.html.
  • Create a list of all possible outcomes of rolling a die.
  • Greet the player and ask them if they like to roll the die. And take the input of the player, which is either a yes or a no.
  • Use a while loop to print the number we got when we rolled the die. We use random.choice() method, to do the same. It will return a random number from the list we have created earlier.
  • Ask the player if they want to roll again, and depending on their input, we will either continue rolling or stop rolling and thank them for playing.
							
							
					import random

l = [1,2,3,4,5,6] #list of all possible outcomes

print("Welcome! Do you wanna roll the dice?") #Greeting the player

r = input() #Taking the input from the player for the first time

#Checking whether the player wants to play or not
if r[0].lower() == 'y':
play = True
else:
play = False

#while loop to simulate the rolling of the die
while play:

print("The number you got is",random.choice(l)) #printing the outcome of rolling of die

print("Do you wanna roll again?") #asking whether they want to play again or not

x = input() # taking the input of the player again

#if player wants to play again the loop continues. else the loop breaks
if x[0].lower() == 'y':
play = True
else:
play = False

print("Thank you for playing") #thanking the player for playing				
			

That’s it our text-based simulator is ready. This simple program will help us to understand the fundamental programming concepts like the decision making(using if-else) and the control flow of a loop.
I have used python because it is beginner-friendly. You can implement this program using any language of your liking. The sole purpose of this post is to induce interest in the people who are not into coding. If you did not understand any part of the code or want to improve the code, feel free to comment down below. That is all for this post, thank you for reading. Until next time!


Cheers!

0 0 votes
Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments