Python Program to Generate a Random Number

P

In this example, you will learn to generate a random number in Python.

To understand this example, you should have the knowledge of following Python programming topics:

  1. WHAT IS PYTHON? THINGS TO KNOW BEFORE CODE WITH PYTHON
  2. HOW DO I GET AND INSTALL PYTHON?
  3. PYTHON PRIMITIVES – VARIABLES, BUILT-IN DATA TYPES, COMMENTS, SYNTAX, AND SEMANTICS
  4. CODING APPROACHES IN PYTHON
  5. STYLE GUIDE FOR PROGRAMMING PYTHON CODE
  6. ERRORS AND EXCEPTIONS IN PYTHON

To generate random number in Python, randint() function is used. This function is defined in random module.

Source Code

# Program to generate a random number between 0 and 9

# import the random module
import random

print(random.randint(0,9))
Output

5

Note that, we may get different output because this program generates random number in range 0 and 9. The syntax of this function is:

random.randint(a,b)

This returns a number N in the inclusive range [a,b], meaning a <= N <= b, where the endpoints are included in the range.

About the author

Pardeep Patel
Pardeep Patel

Add comment

Basics of Python