fbpx

Random

So far, we have interacted with several different instances where we desire to generate an element of randomness in our code. To do this, we can import the random module and utilize some of its key functions. To recap some of these:

  • randint(lower, upper): generates a random integer between the lower and upper bounds, inclusive
  • randrange(lower, upper, [step]): generates a random integer between the lower (inclusive) and upper (exclusive) bounds, with an optional step parameter specifying the step between potential values
  • choice(list): returns a randomly selected element from the list passed as a parameter
  • shuffle(list): randomizes the order of elements within a list
  • sample(list, k): returns a new list containing k randomly selected elements from the passed list

For the sake of the exam, these functions are the extent of what you should need to know. There are many other useful functions within the random module that you can explore here.

Replit Practice

Loading...