Course contentsShow
← Python
Lesson 692 of 1,06011. Standard Library EssentialsFree lesson

Generating Numeric Values with the random Module

Generate integers and floats with random, distinguishing inclusive randint bounds from exclusive randrange stops when choosing numeric ranges.

In this lesson, you will learn how to generate integers and floating-point numbers using the random module while mastering the distinction between inclusive and exclusive boundary behaviors.

Generating Integers: randint vs. randrange

When you need a whole number, Python provides two primary functions that behave differently regarding their range boundaries.

The random.randint(a, b) function is inclusive on both ends. This means if you write randint(1, 10), the result can be any integer from 1 up to and including 10.

In contrast, random.randrange(start, stop) follows the same convention as Python slicing or range(): it is inclusive of the start, but exclusive of the stop. If you write randrange(1, 10), the possible values are 1 through 9.

import random

# randint includes both 1 and 10
val_int = random.randint(1, 10)

# randrange includes 1, but excludes 10
val_range = random.randrange(1, 10)

Generating Floats

For scenarios requiring decimal precision, random.random() is your go-to tool. It returns a float in the range [0.0, 1.0), where 0.0 is included but 1.0 is excluded.

If you need a float within a specific range, such as between 5.5 and 10.5, you can use random.uniform(a, b). Unlike the integer functions, uniform will return a random floating-point number NN such that a≤N≤ba \leq N \leq b (or b≤N≤ab \leq N \leq a). Note that the endpoints are inclusive here, which is a common point of confusion for developers used to the range style of stopping points.

# Returns a random float between 5.5 and 10.5
val_float = random.uniform(5.5, 10.5)

Choosing the right tool ensures your logic stays robust: always remember that randint and uniform lock in their endpoints, while randrange keeps the upper bound exclusive to match standard Python iterator patterns.

Key Takeaway: Use randint(a, b) and uniform(a, b) when you want inclusive boundaries for integers and floats, but use randrange(a, b) when you need to follow the exclusive "stop" index pattern common in Python sequences.