Sitemap
SbCoding

SbCoding

やらないならやらなやるなら本気でやる。

Randomization in Python

1 min readDec 11, 2024

--

Press enter or click to view image in full size
Python’s random module is a fantastic tool for adding unpredictability to your programs. From games to password generators, it’s got you covered. Let’s dive into a few simple examples to understand how it works.

Toss a Coin

Want to make a quick decision? Use Python to flip a virtual coin:

import random

result = random.choice(['Heads', 'Tails'])
print(f"The coin shows: {result}")

Roll a Dice

Simulate a dice roll for your next board game:

import random

dice_roll = random.randint(1, 6)
print(f"You rolled a: {dice_roll}")

Shuffle a Deck

Need to randomize a list? Shuffle it like a pro:

mport random

deck = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
random.shuffle(deck)
print("Shuffled deck:", deck)

Create a Password

Generate a strong, random password effortlessly:

mport random
import string

password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
print(f"Your password: {password}")

Why Use It?

The random module is perfect for games, decision-making, or any scenario where unpredictability is key. Just remember, it’s not suitable for secure encryption—use the secrets module for that.

Get SbCoding’s stories in your inbox

Join Medium for free to get updates from this writer.

Start exploring today, and see how randomization can simplify our projects!

--

--

SbCoding
SbCoding

Written by SbCoding

やらないならやらなやるなら本気でやる。