❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Random Modules in Python: [TBD]

By: Sakthivel
5 August 2024 at 13:54

The random module in Python is used to generate pseudo-random numbers and perform random operations. It provides a variety of functions for generating random numbers, choosing random items, and shuffling sequences. Here are some commonly used functions from the random module:

  1. random.random(): Returns a random float between 0.0 and 1.0.
import random
print(random.random())  # Example output: 0.37444887175646646

2. random.randint(a, b): Returns a random integer between a and b (inclusive).

print(random.randint(1, 10))  # Example output: 7

3. random.choice(seq): Returns a random element from the non-empty sequence seq.

fruits = ['apple', 'banana', 'cherry']
print(random.choice(fruits))  # Example output: 'banana'

4. random.shuffle(lst): Shuffles the elements of the list lst in place.

cards = ['A', 'K', 'Q', 'J']
random.shuffle(cards)
print(cards)  # Example output: ['Q', 'A', 'J', 'K']

5. random.sample(population, k): Returns a list of k unique elements from the population sequence.

numbers = [1, 2, 3, 4, 5]
print(random.sample(numbers, 3))  # Example output: [2, 5, 3]

6. random.uniform(a, b): Returns a random float between a and b.

print(random.uniform(1.5, 6.5))  # Example output: 3.6758764308394

7. random.gauss(mu, sigma): Returns a random float from a Gaussian distribution with mean mu and standard deviation sigma.

print(random.gauss(0, 1))  # Example output: -0.5475243938475568

Remember to import the module using import random before using these functions.

❌
❌