How to Generate Random Numbers in Python: A Beginner’s Guide with Dice Simulations
This tutorial explains Python's built‑in random module, demonstrates simple and interactive scripts for generating pseudo‑random numbers—including dice rolls—and provides step‑by‑step code examples for creating and running these programs on any platform.
What is the random module?
Python's random module is built into the language, so no additional installation is required. It provides several functions for generating pseudo‑random values.
seed() – initializes the random number generator.
getstate() – returns the current state of the generator.
randrange() – returns a random number within a given range (excluding the endpoint).
randint() – returns a random integer between two endpoints (inclusive).
choice() – selects a random element from a sequence.
shuffle() – shuffles a sequence in place.
Simple random number generator
First, a minimal script that generates a single random integer between 0 and 10:
import random
n = random.randint(0, 10)
print(n)Save the code to a file (e.g., simplerand.py) and run it with python3 simplerand.py. Each execution prints a pseudo‑random number in the specified range.
Using randrange() for exclusive bounds
If you prefer to exclude the upper bound, replace randint() with randrange():
import random
n = random.randrange(0, 10)
print(n)More complex dice‑rolling generator
For tabletop games like D&D, you may want to roll dice with various numbers of sides. The following script asks the user for the desired number of sides and then prints a random roll:
import random
number_1 = input("Enter the number of sides on your dice from 3, 6, 10, 20, and 100: ")
n = random.randint(0, int(number_1))
print(n)Save this as rando.py and execute with python3 rando.py. Each run yields a pseudo‑random result between 0 and the chosen maximum.
Adding a loop for continuous rolls
To avoid restarting the program for each roll, wrap the input and output in a while True loop:
import random
while True:
number_1 = input("Enter the number of sides on your dice from 3, 6, 10, 20, and 100: ")
n = random.randint(0, int(number_1))
print(n)Terminate the script with Ctrl+C. This demonstrates basic use of Python's random module for both simple and interactive applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
