PYTHON 100 BOOTCAMP
BOOTCAMP 3일차
성지우
2022. 6. 14. 15:42
0611
오늘의 목표
- conditional statements
- logical operators
- code blocks
- scope
Conditional if / else
특정 조건에 따라 a 또는 b 둘 중 하나 수행
if condition: #우리가 판단할 조건
do this #들여쓰기, 조건 충족 시 수행되는 코드
else: # if 조건 미충족시 수행되는 코드
do this
◎ Draw.io = 어떤 종류의 순서도나 다이어그램도 만들 수 있는 사이트
실습1 - 롤러코스터1
키 120cm 이상만 탑승가능
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print("You can ride the rollercoaster!")
else: # same indentation level
print("Sorry, you have to grow taller before you can ride.")
Comparison operator
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to
Modulo operator
% - 나머지 연산자
ex) 7 % 2 -> 1
실습2 - 짝수 홀수 판별기
# 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if number % 2 == 0: # 짝수는 나머지가 0
print("This is an even number.")
else : #나머지 0이 아닐 경우
print("This is an odd number.")
Nested if / else
중첩 if 문
첫번째 조건이 통과되야만 다음 조건 확인 가능
if condition: # 조건 충족 시 다음 if 문으로 넘어감
if another condition:
do this
else: #두번째 조건 미충족시 실행
do this
else: #첫번째 조건 미충족 시 실행
do this
실습 3 - 롤러코스터 2
나이에 따른 금액 추가
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age <= 18:
print("Please pay $7.")
else:
print("Please pay $12.")
else: # same indentation level
print("Sorry, you have to grow taller before you can ride.")
실습 1의 코드와 이어서 보면 된다.
if / elif / else
if condition1:
do a
elif condition2: #원하는 만큼 조건 추가가능
do b
else:
do this
a, b,c 중 하나만 수행된다.
실습4 - 롤러코스터 3
elif를 이용해 나이대를 더 세분화
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
print("Please pay $5.")
elif age <= 18:
print("Please pay $7.")
else:
print("Please pay $12.")
else: # same indentation level
print("Sorry, you have to grow taller before you can ride.")
실습5 - BMI 2.0
값 해석이 추가됨
# 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
bmi = round(weight / (height ** 2))
#bmi 지수에 따른 결과 해석
if bmi < 18.5:
print(f"Your BMI is {bmi}, you are underweight.")
elif bmi < 25:
print(f"Your BMI is {bmi}, you have a normal weight")
elif bmi < 30:
print(f"Your BMI is {bmi}, you are slightly overweight")
elif bmi < 35:
print(f"Your BMI is {bmi}, you are obese")
else :
print(f"Your BMI is {bmi}, you are clinically obese.")
실습6 - leap year
윤년 계산기
# 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year")
Multiple if
다수의 조건이 있어 앞서 확인한 조건이 참이어도 여러 조건을 확인해야하는 상황
if condition1:
do a
if condition2:
do b
if condition3:
do c
# 세 가지 조건 모두 확인, 모드 참이면 a , b , c 모두 실행
실습7 - 롤러코스터 4
multiple if 를 이용해 사진 구매 여부 추가
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.")
# 계산 가격알려주는 대신 어떤 표를 살 수 있는지 알려줌
#그 다음 사진을 원하는지 물음, 두번째 if 와 같은 들여쓰기에서 -> 120이상시 해당되기에
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.")
실습8 - 피자주문
#내가 작성한 코드
# 🚨 Don't change the code below 👇
print("Welcome to 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 👇
if size == "S":
bill = 15
if add_pepperoni == "Y":
bill += 2
elif size == "M":
bill = 20
else:
bill = 25
if add_pepperoni == "Y":
bill += 3
if extra_cheese == "Y":
bill += 1
print(f"Your final bill is: ${bill}")
# solution code
# 🚨 Don't change the code below 👇
print("Welcome to 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
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}.")
실습9 - 롤러코스터 5
나이대 추가
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.")
elif age >= 45 and age <= 55: # 나이대 추가, and 연산자
print("Everything is going to be ok. Have a free ride on us!")
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.")
if condition1 & condition 2 %condition3
여러 조건이 같은 행의 코드 안에 있을 때
if condition1 & condition2 & condition3:
do
else:
do this
Logical operators
A and B 둘 다 참이면 T
C or D 둘 중 하나 참, 둘 다 참이면 T, 둘 다 거짓이면 F
not E 조건에 반대되는 값, 조건 참이면 F, 조건 거짓이면 T
lower( )
소문자로 표현해주는 함수
count( )
개수를 세어주는 함수
"Angela".lower()
# angela
"Angela".count("a")
# 1
실습10 - Love calculator
한국의 이름점 과 비슷
두 명의 이름에서 t,r,u,e 와 l,o,v,e 와 같은 글자 수를 구해서 점수를 출력
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
combine_name = name1 + name2
lower_combine_name = combine_name.lower()
t = lower_combine_name.count("t")
r = lower_combine_name.count("r")
u = lower_combine_name.count("u")
e = lower_combine_name.count("e")
first_num = t + r + u + e
l = lower_combine_name.count("l")
o = lower_combine_name.count("o")
v = lower_combine_name.count("v")
e = lower_combine_name.count("e")
second_num = l + o + v + e
score = int(str(first_num) + str(second_num))
#first_num 과 second_num은 정수 문자열로 하나로 이어줌-문자열 변환
#if문을 위해 다시 정수형으로 바꿔준다
if score<10 or score>90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif score>=40 and score <=50:
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.")
다중 문자열 출력
print(""" """)
오늘의 프로젝트 - 게임 만들기
# mine
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 == "blue":
print("You enter a room of beasts. Game Over.")
elif choice3 == "yellow":
print("You found the treasure! You Win!")
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.")
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#solution
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 == "blue":
print("You enter a room of beasts. Game Over.")
elif choice3 == "yellow":
print("You found the treasure! You Win!")
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.")