Generate random numbers in Python

Python provides a built-in module called random that allows us to work with random numbers. The random module provides various functions for generating random numbers, such as:

  • randint(): generates a random integer within a given range.
  • random(): generates a random float between 0 and 1.
  • uniform(): generates a random float within a given range.
  • choice(): selects a random element from a sequence (such as a list or a string).
  • sample(): generates a list of random elements from a sequence with replacement.
  • shuffle(): shuffles the elements of a list in place.

Here are some examples of how to use these functions:

 

import random

# Generate a random integer between 1 and 10
random_number = random.randint(1, 10)
print(random_number)

# Generate a random float between 0 and 1
random_number = random.random()
print(random_number)

# Generate a random float between 1 and 10
random_number = random.uniform(1, 10)
print(random_number)

# Select a random element from a list
my_list = [1, 2, 3, 4, 5]
random_element = random.choice(my_list)
print(random_element)

# Generate a list of 3 random elements from a list with replacement
random_elements = random.sample(my_list, k=3)
print(random_elements)

# Shuffle the elements of a list in place
random.shuffle(my_list)
print(my_list)
 

These are the basics of generating random numbers in Python using the random module. I hope this helps.

No comments

Powered by Blogger.