[파이썬] 3강 논리 연산자_코드 비교
3강 '흐름 제어와 논리연산자' 강의에서는 if, elif, else 조건문을 이용해 흐름을 제어하는 방법을 배웠다.
실생활과 비교해보면 보통 '하나의 조건 -> 하나의 결과'로 진행되기 보단 여러가지 조건을 동시에 고려하여 특정한 결과로 귀결되곤 한다.
다중조건을 코드로 정리해나가는 것이 매우 까다로운 부분인데, 그럴때마다 필요한 것이 순서도 그려나가며 각각의 조건을 하나하나 쪼개 생각해 보는 것이다.
1. 내가 쓴 코드
print("Thank you for choosing Python Pizza Deliveries!")
size = input() # What size pizza do you want? S, M, or L
add_pepperoni = input() # Do you want pepperoni? Y or N
extra_cheese = input() # Do you want extra cheese? Y or N
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
bill = 0
if size == "S":
bill = 15
if add_pepperoni == "Y":
bill += 2
elif size == "M":
bill = 20
if add_pepperoni == "Y":
bill += 3
else:
bill = 25
if add_pepperoni == "Y":
bill += 3
if extra_cheese == "Y":
bill += 1
print(f"Your final bill is: ${bill}.")
2. 강의 정답 코드
print("Thank you for choosing Python Pizza Deliveries!")
size = input() # What size pizza do you want? "S", "M", or "L"
add_pepperoni = input() # Do you want pepperoni? "Y" or "N"
extra_cheese = input() # Do you want extra cheese? "Y" or "N"
# Your code below this line 👇
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
else:
bill += 25
if add_pepperoni == "Y":
if size == "S":
bill += 2
else:
bill += 3
if extra_cheese == "Y":
bill += 1
print(f"Your final bill is: ${bill}.")
1번의 내가 쓴 코드는 하나의 조건을 검토할때 다른 조건들도 같이 껴넣으려는 것인데 2번의 정답 코드를 보듯이 다른 속성의 조건(add_pepperoni, extra_cheese)은 과감하게 다른 영역으로 분리하게되니 논리와 순서가 명확하게 이해된다. 두개 코드의 결과는 동일했지만 사고의 과정은 엄연히 달랐다는 점에서 또 배워가는 부분이 있었다.
3일차 프로젝트: 보물섬 게임 설계
매 강의 마지막에는 그날 배운 것들을 종합적으로 활용해볼 수 있는 프로젝트를 진행한다. (프로젝트라기엔 너무 거창하지만 나에게는 크나큰 도전 ㅎㅎㅎ) 아직은 수업내용이 많이 어렵지 않아서 마지막 프로젝트 영상이 기다려지곤 하는데, 이번에도 에러없이 잘 실행되었다. 그치만 다듬어야 할 부분이 꽤 있으므로 정리해본다.
1. 내가 작성한 코드
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#Write your code below this line 👇
direction = input('You are at a cross road. Where do you want to go? Type "left" or "right"')
if direction == "left":
action = input('There is a boat coming. Do you want to swim to reach out or just wait? Type "Swim" or "Wait"')
if action == "Wait":
door = input('One last door is waiting for you. Which door do you choose? Type "Red" or "Blue" or "Yellow"')
if door == "Yellow":
print("You win!!!")
elif door == "Red":
print("You were burned by fire. Game Over.")
elif door == "Blue":
print("You were eaten by beasts. Game Over.")
else:
print("Game Over.")
else:
print("You were attacked by trout. Game Over.")
else:
print("Fall into a hole. Game Over.")
2. 안젤라 선생님의 코드
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#Write your code below this line 👇
choice1 = input('You\'re at a cross road. Where do you want to go? Type "left" or "right" \n').lower()
if choice1 == "left":
choice2 = input('You\'ve come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across. \n').lower()
if choice2 == "wait":
choice3 = input("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose? \n").lower()
if choice3 == "red":
print("It's a room full of fire. Game Over.")
elif choice3 == "yellow":
print("You found the treasure! You Win!")
elif choice3 == "blue":
print("You enter a room of beasts. Game Over.")
else:
print("You chose a door that doesn't exist. Game Over.")
else:
print("You get attacked by an angry trout. Game Over.")
else:
print("You fell into a hole. Game Over.")
- 다중 조건문에서 가장 중요한 것은 들여쓰기(indentation)다. 위 코드에는 총 3개의 조건문이 들어가있다. 조건에 조건이 더해질때마다 들여쓰기가 추가되어야 하며, 한 조건 안에서 비교할 때는 같은 층위에 둔다.
- input함수를 사용해 사용자로부터 어떤 값을 입력 받는 경우(type "left" or "right"), 해당 사용자가 어떤 형식으로 입력할지(즉 대문자로 입력할지, 소문자로 입력할지, 혼용해서 입력할지 등)는 제어하기 까다로운 영역이다. 따라서 입력받은 값이 어떤 형식이든, 동일한 형식으로 처리되게끔 전처리를 해주면 좋다. 위 안젤라 선생님 코드 중 input 함수 끝에 붙어있는 .lower() 함수가 해당한다. 이 경우 어떤 값을 입력받든 소문자로 처리한다는 의미다.