파이썬

AI 웹 개발 공부 3일 차 (사전 캠프)

zhelddustmq 2024. 5. 31. 15:20

1. 자판기 만들기(파이썬)

vending machine(python)

 

#자판기 음료 종류 및 가격이 담긴 딕셔너리
beverages = {
		"사이다": 1700,
		"콜라": 1900,
		"식혜": 2500,
		"솔의눈": 3000
}

#자판기 이용자에게 메뉴 보여주기
for key, value in beverages.items():
    print(key + " " + str(value) + "원")

#음료 선택
user_choice = input("음료를 선택해주세요")
if not user_choice in beverages.keys():
	print("그게 뭔가요?")
	exit()

#자판기에 넣을 금액 입력
coin = input("금액을 입력해주세요")

#정수로 형변환
coin = int(coin)

#금액이 부족할 때와 잔액 출력
if coin < beverages[user_choice]:
		print("돈이 부족합니다")
		exit()
else:
	print("잔액은 " + str(coin - beverages[user_choice]) + "입니다.")

 

 

2. 단어 맞추기(파이썬)

guess_the_word(python)

#랜덤한 것을 코딩할 때 포함되는 라이브러리
import random

#기회
count = 9

#사용자가 내놓는 추측
guess = ""

#프로그램 안에 있는 단어들
word= [
    "airplane",
    "apple",
    "arm",
    "bakery",
    "banana",
    "bank",
    "bean",
    "belt",
    "bicycle",
    "biography",
    "blackboard",
    "boat",
    "bowl",
    "broccoli",
    "bus",
    "car",
    "carrot",
    "chair",
    "cherry",
    "cinema",
    "class",
    "classroom",
    "cloud",
    "coat",
    "cucumber",
    "desk",
    "dictionary",
    "dress",
    "ear",
    "eye",
    "fog",
    "foot",
    "fork",
    "fruits",
    "hail",
    "hand",
    "head",
    "helicopter",
    "hospital",
    "ice",
    "jacket",
    "kettle",
    "knife",
    "leg",
    "lettuce",
    "library",
    "magazine",
    "mango",
    "melon",
    "motorcycle",
    "mouth",
    "newspaper",
    "nose",
    "notebook",
    "novel",
    "onion",
    "orange",
    "peach",
    "pharmacy",
    "pineapple",
    "plate",
    "pot",
    "potato",
    "rain",
    "shirt",
    "shoe",
    "shop",
    "sink",
    "skateboard",
    "ski",
    "skirt",
    "sky",
    "snow",
    "sock",
    "spinach",
    "spoon",
    "stationary",
    "stomach",
    "strawberry",
    "student",
    "sun",
    "supermarket",
    "sweater",
    "teacher",
    "thunderstorm",
    "tomato",
    "trousers",
    "truck",
    "vegetables",
    "vehicles",
    "watermelon",
    "wind"
]

#리스트 요소 랜덤하게 뽑기
temp = random.choice(word)

#뽑은 요소 한글자씩 리스트화 시키기
answer = list(temp)

guessing_answer = []
for i in range(len(temp)):
    guessing_answer.append('_')

while count != 0:
    print("현재 남은 기회 : " + str(count))
    guess = input("A-Z 중 하나를 입력하세요 ")

    #여러개 입력할 경우
    if len(guess) > 1:
        print("하!나!만! 입력하세요. 기회가 1 차감됩니다.")
        count -= 1
        continue

    #대문자까지는 허용 -> 소문자로 변환
    if 'A' <= guess <= 'Z':
        guess = guess.lower()

    #정답이 있는 경우
    if 'a' <= guess <= 'z':
        j = 0
        for i in answer:
            if guess == i:
                guessing_answer[j] = guess
            j += 1
        count -= 1
        '''
        enumerate를 쓸경우
            if 'a' <= guess <= 'z':
        for i, ans in enumerate(answer):
            if guess == ans:
                guessing_answer[i] = guess
                print(i)
        count -= 1
        '''
        print(guessing_answer)
        if answer == guessing_answer:
            print("정답입니다! ", guessing_answer)
            exit()
    #잘못 입력한 경우
    else:
        print("정답에 포함된 알파벳이 아닙니다. 기회가 1 차감됩니다.")
        count -= 1

----------------------------------------------------------

나만의 필수암기노트

 

1. def fnc(*args) : 매개변수의 개수를 얼마든지 받을수 있음

 

예제1

def cal(*args):
	for name in args:
    		print(f'{name} 밥먹어라~')
            
cal('영수','철수')

 

2.  def fnc(**kwargs) : 매개변수들을 딕셔너리 형태로 받음

def cal(**kwargs):
    print(kwargs)

cal(name='bab', age=30, height = 180)

 

3. 삼항 연산자 if, for

#if 삼항 연산자
a= 31
print("odd" if a % 2 == 1 else "even")

#for 삼항 연산자
a = [1,2,3,4,5,6,7]
print([i*2 for i in a])

 

4. map, filter, lambda

4-1 map-> list(map(함수 이름, 변수)) : 변수의 요소들을 함수에 하나하나 대입한 결과를 list로 만듦

4-2 lambda-> list(map(lambda x: x에 관한 명령, 변수)) : 변수의 요소들을 x에 하나하나 넣어 x에 관한 명령을 수행 후 결과를 list로 만듦(리턴값 필요)

4-3 filter-> list(filter(lambda x: x에 관한 조건문, 변수)): 변수의 요소들을 x에 하나하나 넣어 x에 관한 조건을 따진것만 list로 만듦(리턴값 필요x)