You can create random numbers within a specific range in Python using the random
module, which offers several functions for different purposes:
Generating Random Floating-Point Numbers
-
random.random()
: This function returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).import random random_number = random.random() print(random_number) # Output: A random number between 0.0 and 1.0
-
random.uniform(a, b)
: This function returns a random floating-point number N such thata <= N <= b
fora <= b
andb <= N <= a
forb < a
. It includes both endpoints.import random random_number = random.uniform(1.0, 10.0) print(random_number) # Output: A random number between 1.0 and 10.0
Generating Random Integers
-
random.randint(a, b)
: This function returns a random integer N such thata <= N <= b
. It includes both endpoints.import random random_integer = random.randint(1, 10) print(random_integer) # Output: A random integer between 1 and 10 (inclusive)
Summary Table
Function | Returns | Range (inclusive unless noted) | Data Type | Example |
---|---|---|---|---|
random.random() |
Random floating-point number | 0.0 to 1.0 (exclusive of 1.0) | float | random.random() |
random.uniform(a, b) |
Random floating-point number | a to b |
float | random.uniform(1.0, 10.0) |
random.randint(a, b) |
Random integer | a to b |
int | random.randint(1, 10) |
These functions provide flexible ways to generate random numbers within specific ranges in Python, depending on whether you need a floating-point number or an integer.