How to Generate a Random Number in Python

Introduction

Generating random numbers is essential for simulations, games, and data sampling. Let’s explore how to do it in Python!

Importing the Library

First, import the random library. Use this line of code:import random

Generating a Random Integer

To generate a random integer, use: random.randint(a, b)   This returns an integer N such that a ≤ N ≤ b.

Generate a Random Number

For example, to generate a random integer between 1 and 100, use: random_number = random.randint(1, 100)

Store or Print the Random Number

You can either store the generated random number in a variable or print it directly. print("Random number:", random_number)

Run the Code

Run your Python script, and a new random number will be generated every time you run the code.