Python Random Module - Generate Pseudo-random numbers

PYTHON RANDOM MODULE:

reload ! diplomawaale.blogspot.com
Random Module In Python



The Python random module is a standard library module that provides functionality for generating random numbers and making random selections. It allows programmers to introduce randomness into their programs. This is often used in various applications, including simulations, games, statistical analysis, and cryptography.

The module offers functions like random(), which generates random floating-point numbers between 0.0 (inclusive) and 1.0 (exclusive), randint(a, b) to produce random integers within a specified range, and choice(seq) for selecting a random element from a sequence. It also includes functions for shuffling sequences (shuffle(seq)) and sampling unique elements from a population without replacement (sample(population, k)).

The random module is valuable for introducing uncertainty and unpredictability in Python programs, making it a crucial tool for tasks where randomness plays a role.

VARIOUS FUNCTION OF RANDOM MODULE:

The Python random module provides a variety of functions for working with random numbers and randomness in general

1. random.random():

Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).

Useful for obtaining random values within a specific range by scaling and shifting the result.

EXAMPLE:


import random

# Generate a random floating-point number between 0.0 and 1.0
random_number = random.random()
print(random_number)


2.random.randint(a, b):

Generates a random integer within the inclusive range from a to b.

            Useful for obtaining random integers for various applications, like simulations and 

            games.

            EXAMPLE:


import random

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

3.random.choice(seq):

Selects a random element from a sequence (list, tuple, or string).

Helpful for making random selections from a collection of items, such as picking a random card from a deck.

EXAMPLE:


import random

# Randomly select a fruit from a list
fruits = ["apple", "banana", "cherry", "date"]
random_fruit = random.choice(fruits)
print(random_fruit)


4.random.shuffle(seq):

Shuffles the elements of a sequence in place, randomizing their order.

Useful for randomizing the order of items in a list or simulating randomness in card

games.

EXAMPLE:


import random

# Shuffle a list of cards
deck = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
random.shuffle(deck)
print(deck)

5.random.sample(population, k):

Selects k unique random elements from a population (without replacement).

Useful for random sampling from a larger dataset without duplicates, such as conducting surveys or simulations.

EXAMPLE:


import random

# Randomly sample 3 unique elements from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_sample = random.sample(numbers, 3)
print(random_sample)

6.random.seed(seed):

Sets the seed value for the random number generator, which allows for reproducible random sequences.

Important when you want to recreate the same random sequence for debugging or sharing results.

EXAMPLE:


import random

# Set a seed for reproducible random results
random.seed(42)
random_number = random.random()
print(random_number)

7.random.uniform(a, b):

Generates a random floating-point number within the specified range [a, b].

Useful for obtaining random values in a specific numeric interval.

EXAMPLE:


import random

# Generate a random floating-point number between 2.5 and 7.5
random_value = random.uniform(2.5, 7.5)
print(random_value)

8.random.gauss(mu, sigma):

Generates random numbers following a Gaussian (normal) distribution with the given mean (mu) and standard deviation (sigma).

Valuable for simulating random data with a normal distribution, such as modeling measurement errors.

EXAMPLE:


import random

# Generate random numbers following a normal distribution
random_value = random.gauss(0, 1) # Mean (mu) = 0, Standard Deviation (sigma) = 1
print(random_value)

9.random.choices(population, weights=None, k):

Selects k random elements from the population based on optional weights that assign probabilities to each element.

Useful for random sampling with weighted probabilities, like drawing items with different chances of being selected.

EXAMPLE:


import random

# Randomly select a color with weighted probabilities
colors = ["red", "green", "blue"]
weights = [0.2, 0.3, 0.5] # Red: 20%, Green: 30%, Blue: 50%
random_color = random.choices(colors, weights=weights, k=1)
print(random_color)

10.random.getstate() and random.setstate(state):

These functions allow you to get and set the internal state of the random number generator.

Useful for saving and restoring the state of the random generator when you need to continue generating numbers from a specific point.

EXAMPLE:


import random

# Save and restore the random state for reproducibility
initial_state = random.getstate()

random.seed(42)
random_number1 = random.random()
print(random_number1)

random.setstate(initial_state) # Restore the initial state
random_number2 = random.random()
print(random_number2)

 

ROCK-PAPER-SCISSOR GAME BY RANDOM MODULE:

This code implements a simple text-based Rock-Paper-Scissors game in Python. Let's break down the code step by step:

  1. import random: This imports the random module, which is used to generate the computer's choice randomly.
  2. get_player_choice(): This function allows the player to choose Rock, Paper, or Scissors. It uses a while loop to repeatedly prompt the player until they make a valid choice. The player's choice is stored in the player_choice variable.
  3. get_computer_choice(): This function generates the computer's choice randomly using the random.choice() function. The possible choices are "Rock," "Paper," or "Scissors."
  4. determine_winner(player_choice, computer_choice): This function takes the player's choice and the computer's choice as arguments and determines the winner based on the rules of the game. It returns a string indicating the result, which can be "It's a tie!", "You win!", or "Computer wins!"
  5. Main Game Loop:
    • The while True loop represents the main game loop. It continues until the player decides not to play again.
    • It first calls get_player_choice() to get the player's choice and get_computer_choice() to get the computer's choice.
    • It then displays both choices and determines the winner using determine_winner().
    • The result is printed on the screen.
    • The player is asked if they want to play again. If they answer anything other than "yes," the loop breaks, ending the game.

import random

# Function to get the player's choice
def get_player_choice():
while True:
player_choice = input("Choose Rock, Paper, or Scissors: ").strip().capitalize()
if player_choice in ["Rock", "Paper", "Scissors"]:
return player_choice
else:
print("Invalid choice. Please choose Rock, Paper, or Scissors.")

# Function to get the computer's choice
def get_computer_choice():
choices = ["Rock", "Paper", "Scissors"]
return random.choice(choices)

# Function to determine the winner
def determine_winner(player_choice, computer_choice):
if player_choice == computer_choice:
return "It's a tie!"
elif (
(player_choice == "Rock" and computer_choice == "Scissors") or
(player_choice == "Paper" and computer_choice == "Rock") or
(player_choice == "Scissors" and computer_choice == "Paper")
):
return "You win!"
else:
return "Computer wins!"

# Main game loop
while True:
player_choice = get_player_choice()
computer_choice = get_computer_choice()

print(f"You chose: {player_choice}")
print(f"Computer chose: {computer_choice}")

result = determine_winner(player_choice, computer_choice)
print(result)

play_again = input("Do you want to play again? (yes/no): ").strip().lower()
if play_again != "yes":
break


Post a Comment

0 Comments