0
0
PythonHow-ToBeginner · 3 min read

How to Generate Random Number in Python: Simple Guide

To generate a random number in Python, use the random module. For example, random.randint(a, b) returns a random integer between a and b inclusive.
📐

Syntax

The random module provides functions to generate random numbers. The most common function is random.randint(a, b), which returns a random integer between a and b inclusive.

Other useful functions include random.random() for a random float between 0 and 1, and random.uniform(a, b) for a random float between a and b.

python
import random

# Generate a random integer between 1 and 10
print(random.randint(1, 10))

# Generate a random float between 0 and 1
print(random.random())

# Generate a random float between 1.5 and 5.5
print(random.uniform(1.5, 5.5))
💻

Example

This example shows how to generate a random integer between 1 and 100 and print it.

python
import random

random_number = random.randint(1, 100)
print(f"Random number between 1 and 100: {random_number}")
Output
Random number between 1 and 100: 42
⚠️

Common Pitfalls

  • Forgetting to import the random module before using its functions.
  • Using random.randint(a, b) with a greater than b causes an error.
  • Expecting random.random() to return integers; it returns floats between 0 and 1.
python
import random

# Wrong: a is greater than b
# random.randint(10, 5)  # This will raise ValueError

# Right:
print(random.randint(5, 10))
Output
7
📊

Quick Reference

FunctionDescriptionExample
random.randint(a, b)Returns random integer between a and b inclusiverandom.randint(1, 10)
random.random()Returns random float between 0.0 and 1.0random.random()
random.uniform(a, b)Returns random float between a and brandom.uniform(1.5, 5.5)

Key Takeaways

Always import the random module before generating random numbers.
Use random.randint(a, b) to get a random integer between a and b inclusive.
random.random() returns a float between 0 and 1, not an integer.
Ensure the first argument is less than or equal to the second in randint to avoid errors.
Use random.uniform(a, b) for random floats within a range.