0
0
PythonProgramBeginner · 2 min read

Python Program to Generate Random Number in Range

Use import random and then random.randint(start, end) to generate a random number between start and end inclusive.
📋

Examples

Inputstart=1, end=10
OutputRandom number between 1 and 10, e.g., 7
Inputstart=0, end=0
Output0
Inputstart=100, end=105
OutputRandom number between 100 and 105, e.g., 103
🧠

How to Think About It

To generate a random number in a range, first decide the start and end values. Then use a built-in tool that picks a number randomly between those two values, including both ends.
📐

Algorithm

1
Import the random number module.
2
Set the start and end values for the range.
3
Use the function to get a random number between start and end.
4
Print or return the random number.
💻

Code

python
import random

start = 1
end = 10
random_number = random.randint(start, end)
print(f"Random number between {start} and {end}: {random_number}")
Output
Random number between 1 and 10: 7
🔍

Dry Run

Let's trace generating a random number between 1 and 10 through the code

1

Import random module

random module is ready to use

2

Set start and end

start = 1, end = 10

3

Generate random number

random.randint(1, 10) returns 7 (example)

4

Print result

Output: Random number between 1 and 10: 7

StepActionValue
1Import randomModule ready
2Set rangestart=1, end=10
3Generate number7
4Print outputRandom number between 1 and 10: 7
💡

Why This Works

Step 1: Import random module

The random module has functions to create random numbers.

Step 2: Use randint function

random.randint(start, end) picks a random integer including both start and end.

Step 3: Print the result

We show the random number so you can see the output.

🔄

Alternative Approaches

random.randrange()
python
import random
start = 1
end = 10
random_number = random.randrange(start, end + 1)
print(f"Random number between {start} and {end}: {random_number}")
Works like randint but excludes the end value, so we add 1 to include it.
random.uniform() for float
python
import random
start = 1.0
end = 10.0
random_number = random.uniform(start, end)
print(f"Random float between {start} and {end}: {random_number}")
Generates a random floating-point number instead of an integer.

Complexity: O(1) time, O(1) space

Time Complexity

Generating a random number is a constant time operation with no loops.

Space Complexity

Only a few variables are used, so constant space.

Which Approach is Fastest?

random.randint and random.randrange are equally fast; random.uniform is for floats and slightly different use.

ApproachTimeSpaceBest For
random.randintO(1)O(1)Random integer including both ends
random.randrangeO(1)O(1)Random integer excluding end (adjustable)
random.uniformO(1)O(1)Random floating-point numbers
💡
Use random.randint(start, end) for simple integer random numbers including both ends.
⚠️
Forgetting that random.randint includes both start and end, so no need to add 1 to the end value.