Python Tutorial (33) – Example: Random Number Generation

Time: Column:Python views:236

Using the random Module to Generate Random Numbers in Python

In Python, you can use the built-in random module to generate random numbers.

Example 1: Generating a Random Decimal Number

import random

random_number = random.random()
print(random_number)

The random.random() function returns a random floating-point number between 0.0 and 1.0.

Output:

0.7597072251250637

Example 2: Generating a Random Integer with random.randint(a, b)

import random

# Generate a random integer between 0 and 9 (inclusive)
random_number = random.randint(0, 9)
print(random_number)

The random.randint(a, b) function returns a random integer NN such that aNba \leq N \leq b, including both aa and bb.

Output:

4

Example 3: Randomly Selecting an Element from a List with random.choice(sequence)

import random

list1 = [1, 2, 3, 4, 5]
random_element = random.choice(list1)
print(random_element)

The random.choice(sequence) function selects a random element from the given sequence (like a list or a tuple).

Output:

4

Example 4: Shuffling a List with random.shuffle(sequence)

import random

list1 = [1, 2, 3, 4, 5]
random.shuffle(list1)
print(list1)

The random.shuffle(sequence) function randomly reorders the elements in the sequence (in-place).

Output:

[3, 2, 4, 5, 1]

These examples demonstrate basic usage of Python's random module for generating random numbers and manipulating sequences randomly.