12.3.2. random
Table of Contents
Getting Started with `random`
The random module in Python helps you work with randomness: picking random numbers, choosing random items from a list, shuffling items, and more. This is useful for games, simulations, testing, and simple data experiments.
To use it, you must import it:
import random
From now on, you’ll call its functions with random. in front, like random.random().
Basic Random Numbers
`random.random()` — Random Float Between 0 and 1
random.random() returns a random floating-point number $x$ such that:
$$0.0 \le x < 1.0$$
import random
x = random.random()
print(x) # e.g. 0.5384937284Every time you run it, you’ll get (almost always) a different value.
`random.randint(a, b)` — Random Integer in a Range
random.randint(a, b) returns a random integer $n$ such that:
$$a \le n \le b$$
Both ends are included.
import random
dice = random.randint(1, 6) # like rolling a 6-sided die
print(dice)Use this when you want whole numbers, like dice rolls, random IDs in a range, etc.
`random.uniform(a, b)` — Random Float in a Range
random.uniform(a, b) returns a random float $x$ such that:
$$a \le x \le b$$
(Depending on internal details, one end may be slightly less than or equal, but for beginners you can think “between a and b”.)
import random
temperature = random.uniform(18.0, 25.0)
print(temperature) # e.g. 21.45739284Use this when you want a decimal result, such as random positions, prices, or measurements.
Choosing Random Items
Often you don’t just want a number; you want to randomly pick from a list of options.
`random.choice(seq)` — Pick One Random Item
random.choice(seq) picks one random element from a non-empty sequence (like a list or string).
import random
colors = ["red", "green", "blue", "yellow"]
picked_color = random.choice(colors)
print(picked_color)With strings, it picks a random character:
text = "Python"
letter = random.choice(text)
print(letter) # e.g. 't'`random.choices(population, k=...)` — Pick With Replacement
random.choices(population, k=n) returns a list of n elements, and items can repeat (sampling with replacement).
import random
cards = ["A", "K", "Q", "J", "10"]
hand = random.choices(cards, k=3)
print(hand) # e.g. ['K', 'K', '10']
Use choices when repeats are allowed (like rolling a die several times).
`random.sample(population, k=...)` — Pick Without Replacement
random.sample(population, k=n) returns n distinct elements. Items will not repeat (sampling without replacement).
import random
numbers = [1, 2, 3, 4, 5, 6]
picked = random.sample(numbers, k=3)
print(picked) # e.g. [4, 1, 6]This is like drawing cards from a deck without putting them back.
If k is bigger than the size of the population, you’ll get an error.
Shuffling Data
`random.shuffle(seq)` — Shuffle a List In Place
random.shuffle(seq) randomly reorders the items of a list. It changes the list itself and returns None.
import random
cards = ["A", "K", "Q", "J", "10"]
print("Before:", cards)
random.shuffle(cards)
print("After: ", cards)
shuffle only works on mutable sequences (like lists), not on immutable types (like tuples or strings).
More Ways to Generate Random Values
`random.randrange(start, stop[, step])`
random.randrange works like range, but picks one random value from that range.
random.randrange(stop)— pick from0, 1, 2, ..., stop-1random.randrange(start, stop)— pick fromstartup tostop-1random.randrange(start, stop, step)— pick fromstart, start+step, ...up to belowstop
import random
# Random even number from 0 to 8
n = random.randrange(0, 10, 2)
print(n) # e.g. 4Use this when you need a specific step, like picking only even numbers.
Controlling Randomness with Seeds
By default, random results change each time you run the program. Sometimes you want to reproduce the same sequence of “random” values (for testing, examples, tutorials, etc.).
You can do this with random.seed().
`random.seed(x)` — Make Randomness Reproducible
If you set a seed, the sequence of random values becomes repeatable. Use any integer (or other hashable value) as the seed.
import random
random.seed(42) # set the seed
print(random.randint(1, 10))
print(random.randint(1, 10))
print(random.randint(1, 10))
If you run this program again with the same seed (42), you will get the same three numbers in the same order.
If you use a different seed, you’ll get a different, but still reproducible, sequence.
If you call random.seed() without arguments, Python re-initializes randomness based on the current time and system state (back to “unpredictable” behavior).
Simple Practical Examples
Example 1: Coin Toss
import random
coin = random.choice(["heads", "tails"])
print("The coin shows:", coin)Example 2: Rock–Paper–Scissors (Computer’s Move)
import random
options = ["rock", "paper", "scissors"]
computer_move = random.choice(options)
print("Computer chose:", computer_move)Example 3: Random Password-Like String (Very Simple)
This is not secure for real passwords, but shows combining random operations with strings.
import random
import string # standard library for letters, digits, etc.
characters = string.ascii_letters + string.digits
length = 8
password = "".join(random.choices(characters, k=length))
print("Generated password:", password)Notes on Security
The random module is good for games and simulations, but it is not designed for security (like real passwords, tokens, or cryptography).
For security-related randomness, Python has another module, secrets, which is better suited for that purpose (this would be covered in more depth elsewhere if needed).
Quick Summary of Common `random` Functions
random.random()— random float in $[0.0, 1.0)$random.randint(a, b)— random integer in $[a, b]$ (inclusive)random.uniform(a, b)— random float between $a$ and $b$random.choice(seq)— one random element from a sequencerandom.choices(population, k=n)— list ofnelements, with repeats allowedrandom.sample(population, k=n)— list ofndistinct elementsrandom.shuffle(list)— shuffle a list in placerandom.randrange(start, stop[, step])— random value from arangerandom.seed(x)— set seed for reproducible random sequences
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!