Day4: Python's Random Module and Lists: Practical Applications

Day4: Python's Random Module and Lists: Practical Applications

In this lesson, I explored the Random module in Python, which allows us to generate random numbers and perform random selections. I also worked with lists, a fundamental data structure in Python. Below is an overview of the key concepts and projects that I built using these concepts.


?? The Random Module in Python:

The random module provides functions to generate random numbers, which are essential in games and simulations.

Generating Random Integers:

You can generate a random integer between two values using random.randint(a, b).

import random

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

Random Floats:

random.random() generates a random float between 0 (inclusive) and 1 (exclusive).

random_number_0_to_1 = random.random() * 10
print(random_number_0_to_1)  # Outputs a random float between 0 and 10        

Alternatively, random.uniform(a, b) generates a random float between two specified values:

random_number_0_to_1 = random.random() * 10
print(random_number_0_to_1)  # Outputs a random float between 0 and 10        

In Python, a module is a file that contains Python code—functions, variables, and classes—that can be imported and used in other Python programs. Modules allow you to organize your code into separate files, making it more manageable and reusable.

Car Company Example

Let’s say we are a car company, and we want to break our program into different parts or modules, each responsible for different functionalities like engine, design, and safety. This allows us to keep the code clean and organized.

Step 1: Create Different Modules

We can create separate files for each module.

1. engine.py (handles car engine functionalities)

def start_engine():
    return "Engine started."

def stop_engine():
    return "Engine stopped."        

2. design.py (handles car design)

def get_car_model():
    return "Sedan"

def get_color_options():
    return ["Red", "Blue", "Black"]        

3. safety.py (handles car safety features)

def apply_brakes():
    return "Brakes applied."

def airbags_status():
    return "Airbags are functional."        

Step 2: Import and Use These Modules in the Main Program

In the main program file, say main.py, we can import these modules and use their functions to manage the car’s functionalities.

# Importing the modules
import engine
import design
import safety

# Using the modules' functions
print(engine.start_engine())
print("Car model:", design.get_car_model())
print("Available colors:", design.get_color_options())
print(safety.apply_brakes())
print(safety.airbags_status())
print(engine.stop_engine())        

Output:

Engine started.
Car model: Sedan
Available colors: ['Red', 'Blue', 'Black']
Brakes applied.
Airbags are functional.
Engine stopped.        

Summary

  • Modules in Python allow us to organize code into different files for better manageability.
  • In the car company example, each module (engine.py, design.py, safety.py) focuses on a specific functionality of the car.
  • We can then import these modules into our main program to use their functionality.

For more modules visit this https://docs.python.org/3/library/random.html

PAUSE 1: Heads or Tails:

Here's how you can create a coin flip program using the random module:

import random

random_heads_or_tails = random.randint(0, 1)
if random_heads_or_tails == 0:
    print("Heads")
else:
    print("Tails")        

?? Lists in Python:

A list is a collection of items in a particular order. Lists are versatile and can store different types of data, including strings, integers, or even other lists.

Creating a List:

fruits = ["Cherry", "Apple", "Pear"]        

Accessing List Items:

You can access an item in a list using its index, remembering that indexing starts from 0.

print(fruits[0])  # Outputs "Cherry"
print(fruits[-1])  # Outputs "Pear" (last item)        

Modifying List Items:

You can change an item in a list by referencing its index:

fruits[0] = "Orange"  # Changes "Cherry" to "Orange"        

Adding Items to a List:

Use append() to add items to the end of a list.

fruits.append("Banana")        

For More on Lists visit https://docs.python.org/3/tutorial/datastructures.html

PAUSE 2: Banker Roulette:

In this game, a random person is selected to pay for everyone. You can do this using either random.choice() or by generating a random index.

import random

friends = ["Alice", "Bob", "Charlie", "David", "Emanuel"]

# Option 1: Using random.choice()
print(random.choice(friends))

# Option 2: Using a random index
random_index = random.randint(0 , 4)
print(friends[random_index])        

?? Handling IndexError:

An IndexError occurs when you try to access an index that is out of the list's range.

fruits = ["Cherry", "Apple", "Pear"]
print(fruits[3])  # This will raise an IndexError since there is no item at index 3        

To avoid this error, you can use the len() function to check the length of the list:

print(fruits[len(fruits) - 1])  # Safely access the last item        

?? Rock, Paper, Scissors Game:

If you not know how to play this game visit to this link to get more details https://wrpsa.com/

Here, I combined the concepts of random numbers and lists to build a Rock, Paper, Scissors game.

import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

game_images = [rock, paper, scissors]

user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
# Note: it's worth checking if the user has made a valid choice before the next line of code.
# If the user typed somthing other than 0, 1 or 2 the next line will give you an error.
# You could for example write:
# if user_choice < 0 or user_choice > 2:
print(game_images[user_choice])

computer_choice = random.randint(0, 2)
print("Computer chose:")
print(game_images[computer_choice])

if user_choice >= 3 or user_choice < 0:
    print("You typed an invalid number. You lose!")
elif user_choice == 0 and computer_choice == 2:
    print("You win!")
elif computer_choice == 0 and user_choice == 2:
    print("You lose!")
elif computer_choice > user_choice:
    print("You lose!")
elif user_choice > computer_choice:
    print("You win!")
elif computer_choice == user_choice:
    print("It's a draw!")        

?? Key Takeaways:

  • Random Module: Generates random numbers and selections, useful for games and simulations.
  • Lists: Store collections of items and can be accessed or modified using index numbers.
  • IndexError: Occurs when trying to access an index that is out of range in a list.
  • Rock, Paper, Scissors: Combining randomization and list indexing to build interactive games.

Stay tuned as I continue to explore more Python concepts and build exciting projects in my #100DaysOfCode journey! ??

要查看或添加评论,请登录

Muhammad Hanzala的更多文章

社区洞察

其他会员也浏览了