Python: 다중연속 if문

Frigate·2022년 5월 25일
0

Python 기초문법

목록 보기
24/27

학습목표: 다중 연속 if문: 다수의 조건이 있는데, 앞서 확인한 조건이 True여도 나머지 여러 조건을 확인하는 조건문
( if elif else 조건문으로 다중조건 중, 하나의 조건만 확인해봤었는데, 이것의 심화단계임 )

참고자료: 티켓팅 다이어그램 / 다중 연속 if 문

1. 앞선 조건이 True여도, 나머지 조건들을 확인하고 넘어가는 조건문 예시 상황

  • 롤러코스터 매표 후, 사진촬영 포함한 표 구매자에게 3달러 더 청구하는 경우

    나이, 키를 이미 알고 표 값을 정했어도 + 사진촬영 원하는지(Y/N)에 따라 추가 3달러를 청구하는 상황

** 키랑 나이만 확인돼면, 사진 촬영 여부를 묻는 순서의 알고리즘이 되어야겠넹

  • 이 경우, 다중 if조건문 작성해야 함

1) if / elif / else <- 다중 조건중, 하나의 조건만 확인해서 True면 종료되었음 (윗조건이 False라면 다음조건이 맞는가)

: if, elif, else를 사용하되, A,B,C 중 어느 하나만 수행이 된다

if condition1 :
   do A
elif condition2 :
   do B
else :
   do C


2) 다중 if 조건문 <- 윗조건이 True여도, 다음조건도 만족하는지 확인 들어감

: 모든 조건들이 확인될 것이고, 아래 3가지가 모두 참이라면? => A,B,C 모두가 실행된다.

if condition1 :
   do A
if condition2 :
   do B
if condition3 :
   do C


2. 1번에 설명한 롤러코스터 매표 + 사진촬영 여부에따른 3달러 추가청구 여부 코드를 작성하시오

*실행결과

Welcome to the rollercoaster!
What is your height in cm? 180
What is your age? 25
Adult tickets are $12
Do you want a photo taken? Y or No. Y
Your final bill is $15


3. 알고리즘 다이어그램을 짜보시오~

  • 키 120 넘어야 탑승가능. 나이에따라 가격 차이남. 이후 사진촬영 여부에따라 추가금 붙음

  • 나이 12 아래는 5달러, 12이상~18살 아래면 7달러, 18이상이면 12달러

** 12이상 18살 아래 == 18 아래 라고 해석할 수 있음ㅋ 왜냐 이전 조건이 12세 아래는 5달러기때문

Try it

1) 오답

  • 입력함수input()이 받는 데이터형은 str형이 기본임. 때문에 str형을 받는 int함수에 round()를 씌워줄 수 없음

  • 120 이상되야 탑승가능한데 부등호 잘못표기했음

  • 들여쓰기 오류있음 (unindent does not match any other identation level)

height = round(input("Welcom to the rollercoaster! \nWhat is your height in cm? "))
age = int(input("What is your age?"))
if height > 120 :
   print("Can't ride")
elif age < 12 :
  photo = input("Adult tickets are $5 \nDo you want a photo taken? Y or N. ")
  if photo == Y :
    print("The total bill is $8.")
  if photo == N :
    print("The total bill is $5.")
elif age < 18 :
   photo = input("Adult tickets are $7 \nDo you want a photo taken? Y or N. ")
  if photo == Y :
    print("The total bill is $10.")
  if photo == N :
    print("The total bill is $7.")
else :
   photo = input("Adult tickets are $12 \nDo you want a photo taken? Y or N. ")
  if photo == Y :
    print("The total bill is $15.")
  if photo == N :
    print("The total bill is $12.")



2) 오답

  • photo함수가 Y일때 N일때 가정을 완료햇는데, 같은 가정을 아래있는 조건문에 반복으로 써주니까 에러남

    아... 그게 아니고 photo 변수가 담는 Y 또는 N 이 문자형이기 땜에 "" 큰따옴표 안쳐줘서 에러뜬거군

    이렇게 써줘야함.. if photo=="Y":

  • 변수photo는 Y값과 일치할때, B값과 일치할때 결과값 다르므로 if photo = "Y" 이렇게 쓰면 안됌 (아래사진 참고)

height = int(input("Welcom to the rollercoaster! \nWhat is your height in cm? "))
age = int(input("What is your age?"))
if height < 120 :
   print("Can't ride")
elif age < 12 :
  photo = input("Adult tickets are $5 \nDo you want a photo taken? Y or N. ")
  if photo==Y:
    print("The total bill is $8.")
  if photo==N:
    print("The total bill is $5.")
elif age < 18:
   photo = input("Adult tickets are $7 \nDo you want a photo taken? Y or N. ")
   if photo==Y:
    print("The total bill is $10.")
   if photo==N:
    print("The total bill is $7.")
else :
   photo = input("Adult tickets are $12 \nDo you want a photo taken? Y or N. ")
   if photo==Y:
    print("The total bill is $15.")
   if photo==N:
    print("The total bill is $12.")




3) 여러시도 끝에 정답!

height = int(input("Welcom to the rollercoaster! \nWhat is your height in cm? "))
age = int(input("What is your age?"))
if height < 120 :
   print("Can't ride")
elif age < 12 :
  photo = input("Adult tickets are $5 \nDo you want a photo taken? Y or N. ")
  if photo=="Y":
    print("The total bill is $8.")
  if photo=="N":
    print("The total bill is $5.")
elif age < 18:
   photo = input("Adult tickets are $7 \nDo you want a photo taken? Y or N. ")
   if photo=="Y":
    print("The total bill is $10.")
   if photo=="N":
    print("The total bill is $7.")
else :
   photo = input("Adult tickets are $12 \nDo you want a photo taken? Y or N. ")
   if photo=="Y":
    print("The total bill is $15.")
   if photo=="N":
    print("The total bill is $12.")



4) 선생님의 답

  • 표 값은 나이에따라 달라지는 변수므로, 윗문단에 bill 변수 선언해주셨음

  • 키랑 나이에 따른 조건이 확인된 직후, 사진촬영 여부를 키,나이 조건문을 거쳐온 데이터 대상으로 물어봄

    키랑 나이 조건문은 키 다음 나이 묻는 순서라서.. 나이 조건문 블럭에 사진촬영 여부 조건문을 들여쓰기 맞추심.

  • bill = bill + 3 처럼 변수의 값을 높힌후, 다시 변수에 저장하고싶을때 bill+=3 으로 표현 가능함

    변수 bill에 값을 높히는데, 높혀줄 값은 3이다. -> bill+=3

    print("Welcome to the rollercoaster!")
    height = int(input("What is your height in cm? "))
    bill = 0

if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Youth tickets are $7.")
else:
bill = 12
print("Adult tickets are $12.")

wants_photo = input("Do you want a photo taken? Y or N. ")
if wants_photo == "Y":
bill += 3

print(f"Your final bill is ${bill}")

else:
print("Sorry, you have to grow taller before you can ride.")


#유데미 #유데미코리아 #스타트위드유데미 #스터디윗미
profile
Swift

0개의 댓글