3. Random

The random module generates pseudo-random values:

  • random.seed(a) restarts the generator from a known state. The same seed produces the same sequence, which is how the exercises below stay reproducible. Without a seed, Python seeds from the system.
  • random.randint(a, b) returns an integer a <= n <= b; both ends are included.
  • random.random() returns a float 0.0 <= x < 1.0 (it never returns 1.0).
  • random.choice(sequence) returns one random element; the sequence can be a list or a string.
  • random.shuffle(list) changes the list in place and returns None, so print the list after calling it, not the call result.

These numbers are pseudo-random, not secure: never use random to generate passwords or tokens.

Coming from JavaScript? random.random() is Math.random(). random.randint(a, b) includes b, while JS usually needs Math.floor(Math.random() * (b - a + 1)) + a.

#01

Pick a random integer

Import random, call random.seed(7), then print random.randint(1, 6).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Random float between 0 and 1

Import random, call random.seed(1), then print random.random().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Pick from a sequence

Import random, call random.seed(42), then print random.choice(["rock", "paper", "scissors"]).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Shuffle a list

Import random, call random.seed(7), create the list [1, 2, 3, 4, 5], shuffle it with random.shuffle() and then print the list.

Print exactly:

Create a free account to save your progress and unlock chapter 2.