0
0
Pythonprogramming~5 mins

Random data generation in Python

Choose your learning style9 modes available
Introduction

Random data generation helps create unpredictable values. This is useful for games, tests, or simulations.

When you want to simulate rolling a dice in a game.
When you need to pick a random winner from a list of names.
When testing a program with different inputs automatically.
When creating random passwords or codes.
When shuffling a playlist or deck of cards.
Syntax
Python
import random

random_value = random.function(arguments)

You must import the random module first.

Functions like random.randint(a, b) give a random integer between a and b.

Examples
Generates a random number between 1 and 6, like rolling a dice.
Python
import random

number = random.randint(1, 6)
print(number)
Selects a random item from a list of fruits.
Python
import random

choice = random.choice(['apple', 'banana', 'cherry'])
print(choice)
Randomly rearranges the order of items in a list.
Python
import random

shuffled = [1, 2, 3, 4, 5]
random.shuffle(shuffled)
print(shuffled)
Sample Program

This program rolls a dice 5 times and prints each result.

Python
import random

# Simulate rolling a dice 5 times
for i in range(5):
    dice_roll = random.randint(1, 6)
    print(f"Roll {i + 1}: {dice_roll}")
OutputSuccess
Important Notes

Random numbers are not truly random but are good enough for most uses.

Use random.seed() to get repeatable results for testing.

Functions like random.random() give a random float between 0 and 1.

Summary

Random data generation creates unpredictable values for many uses.

Use the random module and its functions like randint, choice, and shuffle.

It is helpful for games, testing, and simulations.