The random module lets us add randomness to our programs. We can generate random numbers, pick random items, or shuffle data. To use it, we must first import it:
import random
To get a random number, use one of the following:
random.randint(1, 10) # Random whole number from 1 to 10 (inclusive)
random.uniform(1.0, 5.0) # Random decimal number between 1.0 and 5.0
You can use this in games, simulations, or decision-making.
To get a random letter or character, try this:
import string
random.choice("abcdef") # Pick a random letter from this string
random.choice(string.ascii_letters) # Random letter from a–z or A–Z
random.choice("!@#$%") # Random symbol
Great for making passwords or codes.
Lists are perfect for choosing random names, actions, or items:
tools = ["sword", "shield", "potion", "bow"]
random.choice(tools) # Pick one random item
random.shuffle(tools) # Shuffle the whole list (changes the list)
random.sample(tools, 2) # Pick 2 random items (no repeats)
Use .shuffle() to mix things up!
Dictionaries need a little trick: choose from their keys or values.
items = {"sword": 10, "shield": 15, "potion": 5}
random.choice(list(items)) # Random key
random.choice(list(items.values())) # Random value
random.choice(list(items.items())) # Random (key, value) pair
This works when you want to pick a random item with its value.
Random whole number
random.randint(1, 10)
Random decimal
random.uniform(1.0, 3.0)
Random string letter
random.choice("abcdef")
Random from a list
random.choice(my_list)
Shuffle a list
random.shuffle(my_list)
Random dictionary key
random.choice(list(my_dict))
Random (key, value) pair
random.choice(list(my_dict.items()))