Kahibaro
Discord Login Register

random

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.5384937284

Every 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.45739284

Use 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.

import random
# Random even number from 0 to 8
n = random.randrange(0, 10, 2)
print(n)  # e.g. 4

Use 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

Views: 11

Comments

Please login to add a comment.

Don't have an account? Register now!