Randomization and Python Lists - Day 04

Randomization and Python Lists - Day 04

ยท

10 min read

100 Days of Code: The Complete Python - Day 04

Today, Goal:

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"))
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")

๐Ÿš€ Random Module

The random module in Python provides a set of functions for generating random values. It is a standard library module, so you don't need to install any additional packages to use it. You can import the random module using the following statement:

import random

Once you have imported the module, you can use various functions to generate random numbers, select random elements, or shuffle sequences. Here are some commonly used functions from the random module:

  1. random(): This function returns a random floating-point number between 0 and 1 (inclusive of 0, but exclusive of 1). Here's an example:

     x = random.random()
     print(x)
    

    Output:

     0.3980935480580328
    
  2. randint(a, b): This function returns a random integer between a and b (inclusive of both a and b). Here's an example:

     x = random.randint(1, 10)
     print(x)
    

    Output:

     7
    
  3. choice(sequence): This function returns a random element from a given sequence (such as a list, tuple, or string). Here's an example:

     numbers = [1, 2, 3, 4, 5]
     x = random.choice(numbers)
     print(x)
    

    Output:

     3
    
  4. shuffle(sequence): This function shuffles the elements in a sequence in-place. It modifies the original sequence directly. Here's an example:

     numbers = [1, 2, 3, 4, 5]
     random.shuffle(numbers)
     print(numbers)
    

    Output:

     [4, 2, 5, 1, 3]
    

These are just a few examples of the functions available in the random module. There are several other functions and methods you can explore, such as uniform(), sample(), choices(), and more, depending on your specific needs for generating random values in Python.

Example:

import random

random_integer = random.randint(1, 10)
print(random_integer)

random_float = random.random() * 5
print(random_float)

love_score = random.randint(1, 100)
print(f"Your love score is {love_score}")

Output: Output will change every time we will re-run the program

# First Time
6
4.058275455184701
Your love score is 9
# Second Time
7
2.2327979342829924
Your love score is 12
# Third Time
2
0.9942541503434588
Your love score is 72

๐Ÿš€ Understanding the Offset and Appending Items to Lists

In Python, lists are ordered collections of items, and you can append new items to the end of a list. When appending items to a list, you don't need to worry about the index or offset manually since Python takes care of it for you.

Let's consider an example to understand how to append items to a list:

my_list = [1, 2, 3, 4]
print(my_list)

my_list.append(5)
print(my_list)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4, 5]

In this example, we have a list my_list initially containing [1, 2, 3, 4]. To append an item to the end of the list, we use the .append() method and provide the item we want to add, in this case, 5. After appending 5 to the list, the updated my_list becomes [1, 2, 3, 4, 5].

Python automatically manages the offset/indexing of the items in the list. The .append() method adds the new item at the next available index, which is always at the end of the list.

Appending items to a list is an efficient way to dynamically grow a collection as you don't need to specify the size in advance. You can append items one by one or even append multiple items using the .extend() method, which takes an iterable as an argument.

Here's an example of extending a list with multiple items:

my_list = [1, 2, 3, 4]
print(my_list)

my_list.extend([5, 6, 7])
print(my_list)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]

In this case, we use the .extend() method to add multiple items [5, 6, 7] to the end of the list. The .extend() method iterates over the provided iterable and appends each item to the list sequentially.

Remember, appending items to a list modifies the original list. If you want to create a new list by adding items from an existing list, you can use the + operator or list comprehension to create a new list with the desired items.

Example:

states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"]

states_of_america[1] = "Pencilvania"

states_of_america.extend(["Angelaland", "Jack Bauer Land"])

print(states_of_america)

Output:

['Delaware', 'Pencilvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii', 'Angelaland', 'Jack Bauer Land']

Explanation:

In the above code, a list called states_of_america is created, containing the names of various states in America.

states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"]

Next, the code modifies the second element (index 1) of the list by assigning a new value to it:

states_of_america[1] = "Pencilvania"

After this assignment, the state name "Pennsylvania" is changed to "Pencilvania" in the states_of_america list.

Then, the code uses the .extend() method to add two new states, "Angelaland" and "Jack Bauer Land", to the end of the states_of_america list:

states_of_america.extend(["Angelaland", "Jack Bauer Land"])

The .extend() method takes an iterable (in this case, a list) as an argument and appends each item in the iterable to the end of the list.

Finally, the code prints the updated states_of_america list:

print(states_of_america)

Output:

['Delaware', 'Pencilvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii', 'Angelaland', 'Jack Bauer Land']

The output displays the updated states_of_america list, which now includes "Pencilvania" instead of "Pennsylvania" and the two newly appended states, "Angelaland" and "Jack Bauer Land", at the end of the list.

๐Ÿš€ IndexErrors and Working with Nested Lists

An IndexError occurs in Python when you try to access an index that is out of range for a list or any other sequence-like object. This error typically happens when you try to access an element using an index that doesn't exist in the list.

Here's an example that demonstrates an IndexError:

my_list = [1, 2, 3]
print(my_list[3])

Output:

IndexError: list index out of range

In this case, my_list has three elements with indices 0, 1, and 2. However, when we try to access my_list[3], which is beyond the range of valid indices, an IndexError occurs because the list index is out of range.

To avoid an IndexError, you should ensure that the index you're trying to access is within the valid range of indices for the list. Remember that in Python, indices start from 0, so the last element in a list can be accessed using the index len(my_list) - 1.

Now, let's move on to nested lists. A nested list is a list that contains other lists as its elements. It allows you to create complex data structures and store multiple levels of information.

Here's an example of a nested list:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this case, nested_list is a list that contains three inner lists. Each inner list represents a row of numbers. You can access individual elements in a nested list using multiple indices.

For example, to access the element 5 in the nested_list, you would use the following indexing syntax:

element = nested_list[1][1]
print(element)

Output:

5

In this case, nested_list[1] gives you the second inner list [4, 5, 6], and nested_list[1][1] accesses the second element within that inner list, which is 5.

Working with nested lists allows you to create more complex data structures and organize data in a hierarchical manner. You can perform various operations, such as indexing, slicing, appending, modifying, and iterating over nested lists, just like you would with regular lists.

Example:

fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears" ]
vegetables = ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"]

dirty_dozen = [fruits, vegetables]

print(dirty_dozen)

Output:

[['Strawberries', 'Nectarines', 'Apples', 'Grapes', 'Peaches', 'Cherries', 'Pears'], ['Spinach', 'Kale', 'Tomatoes', 'Celery', 'Potatoes']]

๐Ÿš€ Day - 4 Assignment

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

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

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

#Write your code below this line ๐Ÿ‘‡

Solution:

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"))
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")

####### Debugging challenge: #########
#Try running this code and type 5.
#It will give you an IndexError and point to line 33 as the issue.
#But on line 39 we are trying to prevent a crash by detecting
#any numbers great than or equal to 3 or less than 0.
#So what's going on?
#Can you debug the code and fix it?

Output:

What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.
5
Traceback (most recent call last):
  File "main.py", line 33, in <module>
    print(game_images[user_choice])
IndexError: list index out of range

By moving the input validation check before accessing the game_images list, we ensure that an invalid input number does not cause an IndexError. Now, when an invalid number is entered, the code will print the error message and exit without attempting to access the list.

Output: Corrected Error

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"))
if user_choice >= 3 or user_choice < 0: 
    print("You typed an invalid number, you lose!") 
else:
    print(game_images[user_choice])

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


    if 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")

Output:

What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.
5
You typed an invalid number, you lose!

If you miss The 100 days of the Python - Day - 01

If you miss The 100 days of the Python - Day - 02

If you miss The 100 days of the Python - Day - 03

#100DaysofCode #Python #Day4

Did you find this article valuable?

Support Ganesh Balimidi by becoming a sponsor. Any amount is appreciated!

ย