if 확장
•
IF조건문 다양한 변환
•
IF문 응용
else문
•
else문 이해와 예시
elif문
•
elif문 이해와 예시
IF문 전체 문법 사용
•
if, elif, else를 이용한 다양한 예시 코드
수업 예시 코드
# 예시 코드
def vending_machine(selection, coins_inserted):
# 음료수 가격과 재고량 설정
drink_prices = {'콜라': 1500, '사이다': 1200, '오렌지주스': 2000}
drink_stock = {'콜라': 5, '사이다': 3, '오렌지주스': 2}
# 선택한 음료수가 있는지 확인
if selection not in drink_prices:
return "선택한 음료수가 없습니다. 다른 음료수를 선택해주세요."
# 선택한 음료수의 가격과 재고 확인
price = drink_prices[selection]
stock = drink_stock[selection]
# 투입한 돈이 충분한지 확인
if coins_inserted < price:
return f"투입한 금액이 부족합니다. {price - coins_inserted}원 더 투입해주세요."
# 음료수가 남아있는지 확인
if stock <= 0:
return "죄송합니다. 해당 음료수는 품절입니다."
# 거스름돈 계산
change = coins_inserted - price
# 음료수 제공 및 재고 감소
drink_stock[selection] -= 1
return f"{selection}이(가) 나왔습니다! 거스름돈 {change}원을 반환합니다."
def quiz_game():
quiz_questions = {
"질문 1": {"답 1": True, "답 2": False, "답 3": False},
"질문 2": {"답 1": False, "답 2": True, "답 3": False},
"질문 3": {"답 1": False, "답 2": False, "답 3": True}
}
correct_answers = 0
for question, answer_options in quiz_questions.items():
print(f"{question}:")
for option, is_correct in answer_options.items():
print(f"{option}")
user_answer = input("답을 선택하세요: ").strip().lower()
# 정답 확인
if user_answer in answer_options and answer_options[user_answer]:
print("정답입니다!\n")
correct_answers += 1
else:
print("틀렸습니다. 다음 문제로 넘어갑니다.\n")
# 결과 출력
print(f"게임 종료! 총 {len(quiz_questions)}문제 중 {correct_answers}문제를 맞추셨습니다.")
Python
복사