Last modified: Mar 30, 2026 By Alexander Williams

Python Random Integer in Range: Generate Numbers

Generating random numbers is a common task in programming.

You might need it for games, simulations, or testing.

Python makes this easy with its built-in random module.

This guide focuses on creating random integers within a specific range.

Why Generate Random Integers?

Random integers have many practical uses.

They are essential for creating unpredictable elements in software.

For example, you can use them to simulate dice rolls in a game.

They are also useful for selecting random samples from data.

Testing often requires random inputs to check program robustness.

Understanding how to control the range is the key skill.

Importing the Random Module

First, you need to import the module. Python does not load it by default.

Use a simple import statement at the top of your script.


import random  # This gives access to all random functions
    

Now you can use functions like randint() and randrange().

Using randint() for Inclusive Ranges

The randint(a, b) function is the most straightforward.

It returns a random integer N where a <= N <= b.

Both the start (a) and stop (b) values are inclusive.

This is different from the standard Python range function which typically excludes the stop value.

If you're curious about this behavior, you can read more in our guide Is Python Range Inclusive? Stop Value Explained.

Let's look at an example to generate a dice roll (1 to 6).


import random

# Simulate a single six-sided dice roll
dice_roll = random.randint(1, 6)
print(f"The dice shows: {dice_roll}")
    

The dice shows: 4
    

Each time you run this, you'll get a number between 1 and 6, including both 1 and 6.

Using randrange() for Flexible Control

The randrange() function offers more flexibility.

It mimics the behavior of the range() function but returns a random element.

Its syntax is randrange(start, stop, step).

The stop value is exclusive, just like in the standard Python Range Function Guide.

You can use it to get random even or odd numbers within a range.


import random

# Get a random even number between 0 and 10 (exclusive)
even_num = random.randrange(0, 11, 2)
print(f"Random even number (0-10): {even_num}")

# Get a random number between 5 and 15 (15 is exclusive)
standard_num = random.randrange(5, 15)
print(f"Random number (5-14): {standard_num}")
    

Random even number (0-10): 6
Random number (5-14): 11
    

Notice how 11 was the stop value for the even number example, so 10 was the maximum possible result.

Key Differences: randint() vs randrange()

Choosing the right function depends on your needs.

randint(a, b): Includes both 'a' and 'b'. Simple for closed ranges.

randrange(start, stop, step): Excludes 'stop'. Powerful for sequences with steps.

Think of randint(1, 10) as picking from 1,2,3,4,5,6,7,8,9,10.

Think of randrange(1, 11) as picking from the same list. The stop is 11 to include 10.

For generating standard sequences, understanding the Python Range Function will help you master randrange().

Common Examples and Use Cases

Let's apply this knowledge to real scenarios.

Example 1: Random Lottery Number Picker


import random

def pick_lottery_numbers(count, max_num):
    """Picks unique random lottery numbers."""
    numbers = []
    while len(numbers) < count:
        new_num = random.randint(1, max_num)
        if new_num not in numbers:  # Ensure no duplicates
            numbers.append(new_num)
    return sorted(numbers)

# Pick 6 unique numbers from 1 to 49
my_ticket = pick_lottery_numbers(6, 49)
print(f"Your lottery numbers: {my_ticket}")
    

Your lottery numbers: [8, 15, 23, 34, 41, 49]
    

Example 2: Random Sampling for a Test


import random

# List of student IDs
student_ids = list(range(101, 151))  # IDs 101 to 150

# Randomly select 5 students for a quiz
selected_students = random.sample(student_ids, 5)
print(f"Selected student IDs: {selected_students}")

# Get a single random participant using randrange
random_index = random.randrange(len(student_ids))
single_participant = student_ids[random_index]
print(f"First presenter: {single_participant}")
    

Selected student IDs: [112, 127, 103, 145, 118]
First presenter: 134
    

Important Considerations and Best Practices

Random numbers in programming are pseudo-random.

They are generated by an algorithm and are predictable if you know the seed.

For most applications, this is perfectly fine.

For cryptography or security, use the secrets module instead.

Always double-check your range boundaries. An off-by-one error is common.

Remember, randint(1, 10) includes 10, but randrange(1, 10) only goes up to 9.

If you need to work with floating-point numbers in sequences, our article on Python Range with Float explores alternative methods.

Conclusion

Generating a random integer in a range is simple in Python.

Use random.randint() for inclusive, straightforward ranges.

Use random.randrange() for exclusive stop values and stepped sequences.

These functions are vital tools for many programming projects.

They add randomness to games, simulations, and data analysis.

Master these basics, and you'll be able to handle most random number generation tasks with confidence.