Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

JINIers

[Python 100 day challenge ] Day 4 본문

공부/Python

[Python 100 day challenge ] Day 4

JINIers 2024. 3. 27. 09:53

day 4는 랜덤모듈을 이용하여 가위바위보 게임을 만들어야한다. (rock, scissors, paper game)


# random

import random
import my_module  # 모듈 불러오기

# 모듈을 불러오면 my_module.pi 안의 내용인 pi = 3.14*** 의 내용이 프린트된다.
print(my_module.pi)

############################################################################
import random

# 1 - 10 중 랜덤
random_integer = random.randint(1,10)
print(random_integer)

# 0.000 - 0.99999...
random_float = random.random()
print(random_float)

# 0.000 - 4.99999...
random_uniform = random.uniform(1, 5)
print(random_uniform)

# other
guass = random.gauss(0,1)
print(guass)        # -0.11779733213241986

ab = random.expovariate(0.1)
print(ab)           # 2.1119162987035565

normal = random.normalvariate(1,7)
print(normal)       # 12.089809562649592

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

# 동전 앞면 & 뒷면

random 모듈을 이용하여 동전 앞면, 뒷면 나오게 하기

1일 때 : 앞면

0일 때 : 뒷

import random
coin = random.randint(0,1)
if coin == 1:
    print("heads")
else:
    print("tails")

 


list

data structure : 데이터를 정리하고 저장하는 방법

* list 의 개념을 이해하는데 조금 어려웠다.

1 ~ 4줄 : 데이터를 list화 함

6줄 : list한 데이터들을 다시 list함(중첩 리스트)

7줄 : list한 data 프린트

8줄 : print 결과값

형광색펜으로 색칠한것처럼 각각의 값을 컬러로 표시했다.

10,11줄처럼 [1][2] 이렇게 중첩하여 프린트하면 그 값에 맞춰 데이터를 뽑아준다.

12줄 : [1][4]는 값이 없으므로 error

 

*세븐틴 좋은 점 : 인원 많아서 언제든지 데이터로 사용가능 ㅋㅋㅋㅋㅋㅋㅋ

 

▼ 아래처럼 강사님의 설명 + 이해한 내용을 텍스트로 정리하긴 했으나 타자로 이해하려니 너무 힘들어서 구냥 내가 필기함

# list
'''
data structure : 데이터를 정리하고 저장하는 방법
'''

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.append("SVT")
states_of_america.append("Caratland")
states_of_america.extend(["Scoups", "JH", "Joshua", "Jun"])

ame = len(states_of_america)
print(states_of_america[ame - 1])



############### 중첩list ###############
dirty_dozen = [ "Strawberries", "Spinach", "Kale", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears", "Tomatoes", "Celery", "Potatoes"]
fruits = [
    "Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries",
    "Pears"
]
vegetables = ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"]

dirty_dozen = [fruits, vegetables]

print(dirty_dozen)
print(
    dirty_dozen[1][2]
)  # dirty_dozen[1] = fruites(0)와 vegetables(1) 중에 1, dirty_dozen[1][2] = vegetables(1) 내의 Tomatoes(2)

 


# 랜덤 식비지불

 

이름 목록에서 무작위로 이름을 선택하는 프로그램을 작성할 것

선택된 사람은 모든 사람의 식비를 지불해야한다.

* choice() 사용X

import random

names = ["scoups", "JH","joshua","jun","wonwoo","woozi","hoshi"]

number = len(names)
rn = random.randint(0, number - 1)

who = names[rn]

print(who)

 

 


# Treasure map

문자-숫자 시스템을 사용하여 지도에 사각형을 표시할 수 있는 프로그램 작성

입력받은 문자 → X 로 변경 후 위치에 표시

line1 = ["⬜️", "️⬜️", "️⬜️"]
line2 = ["⬜️", "⬜️", "️⬜️"]
line3 = ["⬜️️", "⬜️️", "⬜️️"]
map = [line1, line2, line3]
# map = [["⬜️", "️⬜️", "️⬜️"], ["⬜️", "️⬜️", "️⬜️"], ["⬜️", "️⬜️", "️⬜️"]]

position = input("Where do you want to put the treasure? ") # A1 or a1[0][1]

# 문자
letter = position[0].lower()	# 입력받은 문자를 소문자로 변경
let_list = ["a", "b", "c"]
let_index = let_list.index(letter)
print(let_index)

# 숫자
number = int(position[1]) - 1
print(number)

# 입력받은 문자&숫자를 x로 변경
map[let_index][number] = "x"

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

 


# 가위바위보(RPS game)

* 사용해야하는 거 : if/else, random, list

버전이 두개다.

이미지 있는거와 이미지 없는거..

강사님이 코드 짤 때 가위바위보 이미지를 주셨는데 그걸 생각못하고 작성함.

 

1. 이미지 없이 작성

import random

user1_choice = input("what do you choose? Rock,Paper,Scissors.\n").lower()
rps = ["rock", "paper", "scissors"]  # 0 1 2
user1_index = rps.index(user1_choice)

# 컴퓨터
user2_index = random.randint(0, 2)
user2_choice = rps[user2_index]
print("Computer choose : ", user2_choice)

# 바위 = 0, 보 = 1, 가위 = 2
if user1_index == 0 and user2_index == 2:  #바위>가위
    print("이겼어!!")
elif user1_index == 2 and user2_index == 0:  #가위<바위
    print("졌어!!")
elif user1_index == user2_index:  # 가위=가위, 바위=바위, 보=보
    print("비겼어!")
elif user1_index < user2_index:  # 보<가위, 보<바위
    print("졌어!!")
elif user1_index > user2_index:  # 가위>보, 보>바위
    print("이겼어!!")

else:
    print("잘못된 입력입니다.")

 

 

실행결과

 

 

2. 이미지가 띄워도록 작성

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

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

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

#Write your code below this line 👇

import random

image = [rock, paper, scissors]

# user
user_choice = int(input("뭐 낼거니? 0:바위, 1:보, 2:가위\n"))

if user_choice >= 3 or user_choice < 0:
    print("잘못된 입력입니다.")
else:
    user_image = image[user_choice]
    print("user choice : ", user_image)

# computer
computer_choice = random.randint(0, 2)
computer_image = image[computer_choice]
print("computer choice : ", computer_image)

# 확률
if user_choice == 0 and computer_choice == 2:
    print("이겼어")
elif user_choice == 2 and computer_choice == 0:
    print("졌어")
elif user_choice == computer_choice:
    print("비겼어")
elif user_choice > computer_choice:
    print("이겼어")
elif user_choice < computer_choice:
    print("졌어")

 

실행결과

 


가위바위보 버전이 입력하는 값이 좀 다른데

1은 가위바위보 문자를 입력하도록 했고

2는 숫자를 입력해서 이미지로 띄웠다.

문자를 입력해서 이미지로 띄우기도 해봤는데 아직 미천한 실력이라 그렇게 되지 않았음.. ㅜㅜ

어렵긴한데 재미는 있다.

특히 day4는 너무 어려워서 문제를 해결하지 못하고 강의를 봤는데 안젤라가 그쵸 어렵죠. 못풀었다고 좌절하지말고 같이 해결해요 << 하는데 너무 웃기고 ㅋㅋㅋ 위로가 되고 ㅋㅋ 좋았음 ㅋㅋㅋ

 

Comments