Generating a python random number is one of the most common things you will do as a developer. Whether you are building a game, writing a simulation, creating a quiz app, or just need to pick a random item from a list, Python makes it straightforward with its built-in random module. This guide walks you through everything you need to know — from generating your first random integer to shuffling a list and controlling randomness with seeds.
Python ships with a module called random that gives you access to a random number generator. You do not need to install anything. Just import it at the top of your script and you are ready to go.
The numbers produced by this module are technically pseudorandom. That means they are generated by a deterministic algorithm, but the output is statistically random enough for most everyday programming tasks like games, simulations, and sampling. For cryptographic use cases, Python provides a separate secrets module instead.
import random
print(random.random())
0.7412837492018374
Calling random.random() returns a floating point number between 0.0 and 1.0. Every time you run it you get a different value. This is the most basic python random number you can generate.
The most commonly used function for generating a python random number is randint. It takes two arguments — a lower bound and an upper bound — and returns a random integer that includes both endpoints.
import random
dice_roll = random.randint(1, 6)
print("You rolled:", dice_roll)
You rolled: 4
This is perfect for simulating a dice roll. The value will be anywhere from 1 to 6 inclusive. You can change the range to whatever your program needs. Want a number between 1 and 100? Just change the arguments.
While randint always includes both endpoints, randrange gives you more control. It works like Python's built-in range function — the stop value is excluded, and you can optionally provide a step.
import random
even_number = random.randrange(2, 20, 2)
print("Random even number:", even_number)
any_number = random.randrange(10, 50)
print("Random number between 10 and 49:", any_number)
Random even number: 14
Random number between 10 and 49: 33
The first example uses a step of 2, so only even numbers between 2 and 18 are possible. This kind of precision is useful when you need a python random number that fits specific constraints.
Sometimes an integer is not what you need. When you want a python random number that is a decimal, uniform is your go-to function. It returns a float between two values you specify, and both endpoints are included.
import random
temperature = random.uniform(36.1, 37.5)
print(f"Simulated body temperature: {temperature:.2f} degrees")
price = random.uniform(9.99, 49.99)
print(f"Random price: ${price:.2f}")
Simulated body temperature: 36.84 degrees
Random price: $27.53
The format specifier :.2f rounds the float to two decimal places so the output looks clean. This is great for scientific simulations, financial data mocking, or any time you need realistic-looking decimal values.
One of the most practical uses of the random module is picking a random item from a list. The choice function does exactly that — it selects one element at random from any non-empty sequence.
import random
colors = ["red", "green", "blue", "yellow", "purple"]
picked = random.choice(colors)
print("Chosen color:", picked)
directions = ("north", "south", "east", "west")
go = random.choice(directions)
print("Move:", go)
Chosen color: blue
Move: east
This works with lists, tuples, and strings. If you pass a string, it picks a random character. The random number generator python uses internally decides which index to land on, but from your perspective you just get a random item.
What if you need more than one random item, but you do not want repeats? That is what sample is for. It returns a list of unique elements chosen from the population you provide.
import random
lottery_pool = list(range(1, 50))
winning_numbers = random.sample(lottery_pool, 6)
print("Lottery numbers:", sorted(winning_numbers))
Lottery numbers: [3, 14, 22, 31, 37, 45]
The second argument tells sample how many items to pick. The result is always a new list with no duplicates. This is the correct way to simulate drawing cards, selecting winners, or assigning random groups.
The shuffle function randomly reorders the elements of a list directly. It modifies the list in place, meaning it does not return a new list — it changes the original.
import random
deck = ["Ace", "King", "Queen", "Jack", "10", "9", "8"]
print("Before shuffle:", deck)
random.shuffle(deck)
print("After shuffle:", deck)
Before shuffle: ['Ace', 'King', 'Queen', 'Jack', '10', '9', '8']
After shuffle: ['9', 'Ace', 'Jack', '8', 'Queen', '10', 'King']
Every time you run this, the order changes. The python random module's shuffle makes building card games, quiz randomizers, and playlist shufflers simple. Remember that because it modifies in place, your original list is permanently changed unless you make a copy first.
Here is something that surprises many beginners — you can make a random number generator python produce the same sequence every time by setting a seed. When you call random.seed() with a specific value, all subsequent random calls will follow the same predictable sequence.
import random
random.seed(42)
print(random.randint(1, 100))
print(random.randint(1, 100))
print(random.randint(1, 100))
print("--- Resetting seed ---")
random.seed(42)
print(random.randint(1, 100))
print(random.randint(1, 100))
print(random.randint(1, 100))
82
15
4
--- Resetting seed ---
82
15
4
Both runs produce identical output because the seed resets the internal state of the pseudorandom number generator. This is incredibly useful for debugging, writing reproducible experiments, and unit testing code that involves randomness.
The choices function (note the plural) lets you pick items with custom probabilities. You pass a weights list alongside your population and it picks based on those relative weights.
import random
outcomes = ["win", "lose", "draw"]
weights = [1, 3, 1]
results = random.choices(outcomes, weights=weights, k=10)
print("10 game results:", results)
10 game results: ['lose', 'lose', 'win', 'lose', 'draw', 'lose', 'lose', 'draw', 'lose', 'win']
In this example lose is three times more likely to be picked than win or draw. The k argument controls how many picks to make. Unlike sample, choices allows repetition — the same item can appear multiple times in the result.
For scientific simulations, you often need a python random number that follows a bell curve distribution rather than a flat uniform one. The gauss function generates numbers following a normal distribution defined by a mean and standard deviation.
import random
heights = [random.gauss(170, 10) for _ in range(8)]
formatted = [f"{h:.1f}" for h in heights]
print("Simulated heights (cm):", formatted)
Simulated heights (cm): ['168.3', '181.2', '163.7', '174.5', '159.1', '178.8', '172.0', '165.6']
Most values cluster around 170 because that is the mean, with fewer values appearing further away. This is realistic for simulating biological measurements, test scores, or any real-world dataset that follows a natural distribution.
This final program brings together several functions from the python random module to simulate a simple card game setup — dealing hands to players from a shuffled deck.
import random
def build_deck():
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
return [f"{rank} of {suit}" for suit in suits for rank in ranks]
def deal_hands(num_players, cards_each, seed=None):
if seed is not None:
random.seed(seed)
deck = build_deck()
random.shuffle(deck)
if num_players * cards_each > len(deck):
print("Not enough cards in the deck.")
return
hands = {}
for i in range(1, num_players + 1):
hand = random.sample(deck, cards_each)
for card in hand:
deck.remove(card)
hands[f"Player {i}"] = hand
return hands
def display_hands(hands):
for player, hand in hands.items():
print(f"\n{player}'s hand:")
for card in hand:
print(f" - {card}")
def main():
print("=== Card Game Simulator ===\n")
num_players = 3
cards_per_player = 5
print(f"Dealing {cards_per_player} cards to {num_players} players...\n")
hands = deal_hands(num_players, cards_per_player, seed=99)
display_hands(hands)
print("\n--- Bonus Round: Random Multiplier ---")
multiplier = random.uniform(1.5, 3.0)
print(f"Score multiplier this round: {multiplier:.2f}x")
print("\n--- Lucky Number Draw ---")
lucky = random.randint(1, 52)
print(f"Lucky card position: {lucky}")
print("\n--- Player Order Randomized ---")
players = [f"Player {i}" for i in range(1, num_players + 1)]
random.shuffle(players)
print("Turn order:", " -> ".join(players))
main()
=== Card Game Simulator ===
Dealing 5 cards to 3 players...
Player 1's hand:
- 9 of Hearts
- K of Clubs
- 4 of Spades
- J of Diamonds
- 2 of Hearts
Player 2's hand:
- 7 of Clubs
- A of Spades
- 6 of Hearts
- Q of Diamonds
- 10 of Clubs
Player 3's hand:
- 3 of Diamonds
- 8 of Spades
- 5 of Hearts
- K of Hearts
- J of Clubs
--- Bonus Round: Random Multiplier ---
Score multiplier this round: 2.17x
--- Lucky Number Draw ---
Lucky card position: 38
--- Player Order Randomized ---
Turn order: Player 2 -> Player 1 -> Player 3
This example uses shuffle to randomize the deck, sample to deal unique cards without repeats, seed to keep results reproducible, uniform to generate a float multiplier, randint for a lucky number, and shuffle again for turn order. Every function covered in this guide appears in a real working context you can run directly.