본문 바로가기
Coding : Python

Python_Day 4

by Jackykim 2023. 11. 17.

Python Day 4_Randomisation and Python Lists

Randomization
We use import random as a starting point. We can use randint(a, b) which will return a random integer between a and b (both inclusive).

import random

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

Module
When the codes / scripts becomes too complicated or too long we can split them into different modules. This allows different people to work on different modules at the same time to increase efficiency and effectiveness.
You can save a module and import it such as
inport my_module
print(my_module.pi)

Random floating number
random_float = random.random
print(random_float)

Heads or tail coding exercise
You are going to write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails".
There are many ways of doing this. But to practice what we learnt in the last lesson, you should generate a random number, either 0 or 1. Then use that number to print out "Heads" or "Tails".

import random

random_integer = random.randint(0, 1)

if random_integer == 1:

 print("Heads")

else:

 print("Tails")

Data Structure & lists
Set of brackets with many items stored in them such as
fruits = [item1, item2]

For lists the items in the bracket will be separated by a bracket
fruits = [“apple”, “cherry”, “orange”]
fruits[1] = “apple / fruits[-1] = “orange”


You can alter anything or add anything in the list
fruits[1] = “grapes”
print(fruits) = [‘grapes’, ‘cherry’, ‘orange’]
To add something to the list at the end we use the .append function
fruits.append(“apples”)
print(fruits) = [grapes, cherry, orange, apples]

Banker Roulette – Who will pay the bill? Coding exercise
You are going to write a program that will select a random name from a list of names. The person selected will have to pay for everybody's food bill.

Important: You are not allowed to use the choice() function.

names = names_string.split(", ")

# The code above converts the input into an array separating

#each name in the input by a comma and space.

# 🚨 Don't change the code above 👆

import random

 

# Get the total number of items in list

num_items = len(names)

# generate random numbers between 0 and the last index

random_choice = random.randint(0, num_items - 1)

# Pick out random person from the list of names using the random number.

person_who_will_pay = names[random_choice]

print(person_who_will_pay + " is going to buy the meal today!")

 

Indexerrors and working with nested lists
indexerror : list index out of range

Nested lists : when you have multiple lists in a list. If there is a certain list with different category or information that you want to separate you can use nested list.
dirty_dozen = [“Strawberries”, “Spinach”, “apples”, “Kale”, “Grapes”, “Tomatoes”
Fruits = [“Strawberries”, “Apples”, “Grapes”]

Vegetables = [“Spinach”, “Kale”, “Tomatoes”]

we can insert two list such as dirty_dozen = [Fruits, Vegetables]
When you print(dirty_dozen) to will show the whole items from both fruits and vegetable and will be separated by brackets to let you know the two different lists.

Print(dirty_dozen) = [“Strawberries”, “Apples”, “Grapes”], [“Spinach”, “Kale”, “Tomatoes”]
if we print(dirty_dozen[1][1]) = the first [1] will select the vegetable due to code numbers then select [1] from that list which is “Kale”

 

Treasure map coding exercise
You are going to write a program that will mark a spot on a map with an X.

In the starting code, you will find a variable called map.

line1 = ["
️","️️","️️"]

line2 = ["️","️","️️"]

line3 = ["️️","️️","️️"]

map = [line1, line2, line3]

print("Hiding your treasure! X marks the spot.")

position = input() # Where do you want to put the treasure?

# 🚨 Don't change the code above 👆

# Write your code below this row 👇

# Grab the first letter in the input

letter = position[0].lower()
# listing all the possible column letters on the map

abc = ["a", "b", "c"]
# Allows to find the its index in the abc list
# This step determines the column index where the “X” will be placed on the map

letter_index = abc.index(letter)
# The second character is converted to an integer
# The int(position[1] extracts the second character of the user’s input (the number)
# -1 is used to adjust that python starts with 0

number_index = int(position[1]) - 1

map[number_index][letter_index] = "X"

 

# Write your code above this row 👆

# 🚨 Don't change the code below 👇

print(f"{line1}\n{line2}\n{line3}")

Project 4 : Rock paper Scissors
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("Invalid number, you lose")

else:

    print(game_images[user_choice])

 

    import random

    computer_choice = random.randint(0, 2)

    print("computer_choice:")

    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 user_choice == computer_choice:

        print("Its a draw")

 

'Coding : Python' 카테고리의 다른 글

Python_Day 6  (0) 2023.11.30
Python_Day 5  (1) 2023.11.23
Python_Day 3  (0) 2023.11.15
Python_Day 2  (0) 2023.11.10
Python_Day 1  (0) 2023.11.10