Ad space (banner)
🐍Python Lessons
Lesson 54 / 69

Generating Random Numbers

This lesson covers generating random numbers with the random module, so you can build programs with random elements like dice or a lottery. It's written for anyone searching "Python random number generation".

The random module lets you get a random number, or randomly pick one item from a list. Use it for programs like a dice roll or a lottery drawing — the result changes every time you run it. random.randint(min, max) gives an integer in the given range, and random.choice(list) picks one item at random from a list.

The sample code rolls a die from 1 to 6 with random.randint(1, 6), and picks one option at random from a "rock, paper, scissors" list with random.choice(choices). Try reloading and running it a few times to confirm the result changes each time.

A common beginner mistake is misunderstanding the range for random.randint(). randint(1, 6) includes both 1 and 6 in its range — a nice bit of Python friendliness, since you don't need the kind of boundary math that JavaScript's Math.random()-based approach requires.

If you need to reproduce the exact same sequence of "random" numbers, for testing purposes, you can fix the seed with random.seed(). It's an essential basic module whenever you want to introduce unpredictable elements — game shuffle effects, simulation sampling, and more.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)