Python Random Module Generate Random Numbers and More

Python Random Module

The Python random module is a built-in tool for generating random numbers, making it ideal for creating unpredictability in your programs. Whether you’re simulating dice rolls, choosing a random item from a list, or building a game, the random module has a variety of functions to suit your needs. Here’s an overview of some essential functions and how they can add a dynamic edge to your Python projects.

The random() Function

The random.random() function generates a floating-point number between 0.0 and 1.0. It doesn’t require any arguments, making it a straightforward way to introduce randomness.

# Generating a random float
import random
num = random.random()
print(num)

Output:

0.3232640977876686

The randint() Function

For whole numbers, random.randint() provides a simple way to generate a random integer within a specified range. The beginning and ending of the range (inclusive) are the two parameters that the function takes in.

# Producing an arbitrary integer from 1 to 500

import random
num = random.randint(1, 500)
print(num)

Output:

215

Download New Real Time Projects :-Click here

The randrange() Function

The random.randrange() function is similar to randint(), but it allows for more customization by including a step parameter. This function randomly selects a number from a given range, defined by start, stop, and step arguments. The default values for start and step are 0 and 1, respectively.

# Generating values within a specific range
import random
num1 = random.randrange(1, 10)
num2 = random.randrange(1, 10, 2)
print(num1, num2)

Output:

4
9

The choice() Function

Need a random item from a sequence?Choosing a random element from a non-empty sequence—whether it be a string, list, or tuple—is made simple with random.choice().

# Selecting a random element
import random
random_char = random.choice('Random Module')  # from a string
print(random_char)

random_num = random.choice([23, 54, 765, 23, 45, 45])  # from a list
print(random_num)

random_tuple = random.choice((12, 64, 23, 54, 34))  # from a tuple
print(random_tuple)

Output:

M
765
54

The shuffle() Function

The random.shuffle() function is useful when you want to reorder elements in a list. This function randomly changes the order of items within the list, making it a go-to option for shuffling cards or mixing up game elements.

# Shuffling elements in a list
import random
list1 = [34, 23, 65, 86, 23, 43]
random.shuffle(list1)
print(list1)

Output:

[23, 43, 86, 65, 34, 23]

Rock-Paper-Scissors Game Using random

Let’s bring it all together with a simple Rock-Paper-Scissors game that relies on random.randint() for the computer’s choice. This game demonstrates how randomness enhances interactivity in programs.

# Rock-Paper-Scissors Game
import random

def start_game():
    print("Welcome to Rock-Paper-Scissors!")
    print("1: Rock\n2: Paper\n3: Scissors")
    user_choice = int(input("Select an option (1-3): "))

    machine_choice = random.randint(1, 3)
    choices = ["Rock", "Paper", "Scissors"]
    print(f"Machine chose: {choices[machine_choice - 1]}")

    if user_choice == machine_choice:
        print("It's a tie!")
    elif (user_choice == 1 and machine_choice == 3) or (user_choice == 2 and machine_choice == 1) or (user_choice == 3 and machine_choice == 2):
        print("You won!")
    else:
        print("The machine won.")

    if input("Play again? (yes/no): ").lower() == "yes":
        start_game()

start_game()

https://updategadh.com/category/php-project

Additional random Module Functions

The random module also includes various functions to generate numbers and work with sequences:

  • seed(a=None, version=2): Initializes the random number generator with an optional seed.
  • getstate() and setstate(state): Save and restore the generator’s state.
  • getrandbits(k): Generates an integer with k random bits.
  • uniform(a, b): Returns a random float within the specified range [a, b].
  • normalvariate(mu, sigma): Generates a random float based on the normal distribution.

  • python random randint
  • random module in python with example
  • python random float
  • python random number
  • Python Random Module
  • random.sample python
  • python random number in range
  • python random uniform
  • Python Random Module
  • random module in python pdf
  • python compiler
  • python
  • python random module example
  • python random module w3schools
  • random sample python
  • Python Random Module Generate Random Numbers and More
See also  Chapter 9: Object-Oriented Programming OOP in Python

Post Comment