Python Project No.1: Dice Roller

The Idea of Dice Roller

Actually, lots of articles mentioned Dice Roller for beginner’s python project. It involves the following functions/statements:

  • Random
  • Integer
  • Print
  • While

I chose this as my No.1 project, because I roll dices a lot in Dungeons and Dragons and it could be utilized in other projects that I might develop in the future.

Run Python on MacOS

Before digging into code, I should mention that Python scripts that involve user input cannot be run directly through code editor like Atom as it can only generate output. To run those Python scripts, we need to use Terminal.

# navigate to working folder
cd /Users/username/Documents/
# run python file

Code - Dice Roller

Here is the code for Dice Roller.

#import random module
import random

min = 1
max = 6

reroll = "yes"

#roll dice again?
while reroll =="yes" or reroll == "y":
    print("Rolling the dice...")
    print("The values are....")
    print(random.randint(min, max))

    reroll = input("Roll the dice again? ")

I made some changes to accomodate uppercase input.

#original code:
while reroll =="yes" or reroll == "y":

#accomodate both upper and lower case:
while reroll.lower() in ("yes","y"):

Note that in the original code, the while loop will not run if the user input “Y” or “YES”. The updated version is able to accomodate more scenarios as we extend to case-insensitive cases.

Function: Random Integer

random.randint(a, b)

In the Dice Roller, the result is generated by random.randint, which is a random function that returns a random integer a <= N <= b. If we want to make a D20 roller –– D&D players should be familiar with it –– we can change max = 6 to max = 20.

random.randrange(start, stop[, step])

It’s another random function that returns a randomly element, but the result is selected from a range(start, stop, step).

Another equivalent is choice(range(start, stop, step)), but doesn’t actually build a range object.

Note the difference with the former one is that it’s not an include relation. If we would like achieve the same result, the code would be randrange(a, b+1).