Python Tutorials

Python Programs

Python Generate a Random Number


Python Generate a Random Number

In this tutorial, we will learn how to generate a random number in Python. We will cover the basics of using the 'random' module to generate random integers.


What is Random Number Generation

Random number generation is the process of producing a number that is unpredictable and does not follow a specific pattern. In Python, the 'random' module provides various methods to generate random numbers.


Syntax

The syntax to generate a random number in Python using the 'random' module is:

import random
random.randint(a, b)


Generating a random integer between two values

We can use the 'random.randint' method to generate a random integer between two specified values (inclusive).

For example,

  1. Import the 'random' module.
  2. Use the random.randint(a, b) method to generate a random integer between a and b.
  3. Print the generated random number.

Python Program

import random

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

# Print the random number
print('Random number between 1 and 10:', random_number)

Output

Random number between 1 and 10: 7


Generating a random floating-point number

We can use the 'random.uniform' method to generate a random floating-point number between two specified values.

For example,

  1. Import the 'random' module.
  2. Use the random.uniform(a, b) method to generate a random floating-point number between a and b.
  3. Print the generated random number.

Python Program

import random

# Generate a random floating-point number between 1 and 10
random_float = random.uniform(1.0, 10.0)

# Print the random number
print('Random floating-point number between 1.0 and 10.0:', random_float)

Output

Random floating-point number between 1.0 and 10.0: 4.523