🎲

How to Generate Random Numbers in Python

PythonBeginner

Create random numbers and choices with the random module.

Code Example

Python
import random

# Random integer
print(f"Random int (1-10): {random.randint(1, 10)}")

# Random float
print(f"Random float (0-1): {random.random():.4f}")

# Random float in range
print(f"Random float (5-10): {random.uniform(5, 10):.2f}")

# Random choice from list
colors = ["red", "blue", "green", "yellow"]
print(f"\nRandom color: {random.choice(colors)}")

# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"\nShuffled: {numbers}")

# Random sample (without replacement)
print(f"\nSample of 3: {random.sample(colors, 3)}")

# Set seed for reproducibility
random.seed(42)
print(f"\nWith seed: {random.randint(1, 100)}")

Explanation

The random module generates random numbers. Use randint() for integers, random() for floats, choice() for selections, shuffle() to randomize lists.

Related Tutorials