
욕조에 물을 계속 틀어놓으면 언젠가 넘쳐 흐르게(overflow) 되지만,
물이 일정 수위에 도달하는 위치에 배수구(condition)가 있다면 넘치는 것을 막을 수 있는 것과 같음
if / else 구조
if condition: # 조건이 참일 경우 if문 실행
do this # if문의 코드블록
else: # 조건이 거짓일 경우 else문 실행
do this # else문의 코드블록
water_level = 50 # 수위
if water_level > 80:
print("Drain water")
else:
print("Continue")
조건으로 쓰기 위해서는 참 또는 거짓 둘 중 하나로 판명할 무언가가 있어야 함
| 연산자 | 뜻 |
|---|---|
| A > B | A는 B 초과 |
| A < B | A는 B미만 |
| A >= B | A는 B 이상 |
| A <= B | A는 B 이하 |
| A == B | A는 B와 같음 |
| A != B | A는 B와 같지 않음 |
# 롤러코스터 티켓 부스
# 1. 탑승자의 키가 탑승 가능 조건을 만족시키는지 체크
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print("you can ride the rollercoaster")
else:
print("sorry, you have to grow taller before you can ride")
% : 나눈 후 나머지를 구하는 연산자
Odd or Even
입력한 숫자가 짝수인지 홀수인지 알려주는 프로그램
number = int(input())
if number % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.")
중첩 if문 구조
if condition: # 1번째 조건이 참일 경우 if문 실행
if another condition: # 2번째 조건도 참이면 중첩된 if문 실행
do this
else: # 1번째 조건은 참, 2번째 조건은 거짓이면 중첩된 else문 실행
do this
else: # 1번째 조건이 거짓일 경우 else문 실행
do this
if / elif / else 구조
if condition1: # 조건1이 참일 경우 if문 실행
do A
elif condition2: # 조건1이 거짓일 경우 elif문 실행
do B
else: # 모든 조건이 거짓일 경우 else문 실행
do C
# 롤러코스터 티켓 부스
# 2. 탑승이 가능한 사람에 한하여 티켓 금액을 나이에 맞게 차등 적용
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
# if / else 문 (키 체크)
if height >= 120:
print("you can ride the rollercoaster")
age = int(input("what is your age? "))
# if문 안의 if / elif / else문 (나이 체크)
if age < 12:
print("please pay $5")
elif age <= 18:
print("please pay $7")
elif age < 60:
print("please pay $12")
else:
print("please pay $6")
else:
print("sorry, you have to grow taller before you can ride")
BMI 2.0
BMI 계산기 업그레이드 버전
Day2. BMI 계산기
| underweight ~18.5 | normal weight 18.5~25 | slightly overweight 25~30 | obese 30~35 | clinically obese 35~ |
|---|
height = float(input())
weight = int(input())
BMI = weight / height ** 2
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.")
Leap Year
입력한 년도가 윤년인지 아닌지 알려주는 프로그램
- 윤년(leap year) : 2월이 평년보다 1일 더 많아 366일이 되는 해
- 을 만족하면 윤년
- 단, 도 만족하면 평년
- 단, 도 만족하면 윤년
year = int(input())
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")
다중 연속 if문 구조
if condition1: # 조건1이 참일 경우 if문 실행
do A
if condition2: # 조건2가 참일 경우 if문 실행
do B
if condition3: # 조건3이 참일 경우 if문 실행
do C
모든 조건이 확인되며, 모두 참이라면 A, B 와 C가 모두 실행됨
# 롤러코스터 티켓 부스
# 3. 티켓에 사진 구매 옵션 넣기
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
# 금액을 저장하는 변수 초기화
bill = 0
# if / else 문 (키 체크)
if height >= 120:
print("you can ride the rollercoaster")
age = int(input("what is your age? "))
# if문 안의 if / elif / else문 (나이 체크)
if age < 12:
bill = 5
print("child tickets are $5")
elif age <= 18:
bill = 7
print("youth tickets are $7")
elif age < 60:
bill = 12
print("adult tickets are $12")
else:
bill = 6
print("senior tickets are $6")
wants_photo = input("do you want a photo taken? Y or N ")
# 다중 연속 if문 (사진 촬영 옵션 체크)
if wants_photo == "Y":
bill += 3
# 사진 촬영 안 하면 아무것도 안 해도 되기 때문에 else문 생략 가능
print(f"your final bill is ${bill}")
else:
print("sorry, you have to grow taller before you can ride")
Pizza Order Practice
피자 주문 옵션을 체크한 후 최종 금액을 계산하는 프로그램
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
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
elif size == "L":
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}.")
| 연산자 | 의미 |
|---|---|
| A and B | A와 B가 둘 다 참 = 참 |
| C or D | C와 D 둘 중 하나 이상 참 = 참 |
| not E | E의 명제의 반대 |
# 롤러코스터 티켓 부스
# 4. 논리 연산자로 나이 조건 수정
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:
print("everything is going to be ok. have a free ride on us!")
elif age < 60:
bill = 12
print("adult tickets are $12")
else:
bill = 6
print("senior tickets are $6")
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")
string.lower( )
txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
string.upper()
string.capitalize()
string.title()
list.count( value )
value : string, number, list, tuple 등points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
print(x)
Love Calculator
이름 궁합을 계산하는 프로그램
1. 궁합을 볼 두 사람의 이름을 적음
name1 = "Angela Yu"
name2 = "Jack Bauer"
2. "TRUE"에 속한 각 알파벳이 두 사람 이름에서 총 몇 번 등장했는지 센 후, 숫자를 모두 더하기
T occurs 0 times
R occurs 1 time
U occurs 2 times
E occurs 2 times
Total = 5
3. 같은 방법으로 "LOVE"도 체크
L occurs 1 time
O occurs 0 times
V occurs 0 times
E occurs 2 times
Total = 3
4. 두 숫자를 이어붙임
Love Score = 53
5. 점수 집계
a. ~10 또는 90~ : you go together like coke and mentos
b. 40~50 : you are alright together
c. etc. : -
print("The Love Calculator is calculating your score...")
name1 = input() # What is your name?
name2 = input() # What is their name?
combined_names = name1 + name2
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
# love의 e는 true에서 선언했기 때문에 생략
true = str(t + r + u + e)
love = str(l + o + v + e)
score = int(true + love)
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}.")
매 순간 선택에 따라 이야기가 전개되는 오픈 결말 어드벤쳐 게임의 간단한 버전
보물상자 그리기 : ASCII ART
🔍 유의 사항
- 여러 행에 걸쳐 ASCII 아트를 그리기 위해 위와 아래를 ''' 나 """ 로 감싸기
- 문자열 안에서 코드로 인식되는 '(아포스트로피), 따옴표 등을 처리해야 함
': \ 로 무시 가능', ": Day1. 문자열 안에 따옴표 표기 방법- 유저가 선택지를 입력할 때,
- 소문자와 대문자를 보기와 다르게 바꿔 입력해도 명령이 항상 작동되어야 함
- lower() 함수로 입력을 모두 소문자로 변경
- 선택지에 없는 단어를 입력하는 것도 역시 Game over
- 옳은 선택지가 참이면 if문을 실행, 나머지는 else문을 실행하는 구조
- 순서도를 작성하면 원활한 흐름 제어에 도움이 됨
⌨️ 작성한 코드
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.______________|_____________________|_______
| | ,-"_,="" `"=.| |
|___________________|__"=._o`"-._ `"=.______________|___________________
| `"=._o`"=._ _`"=._ |
_________|_____________________:=._o "=._."_.-="'"=.__________________|_______
| | __.--" , ; `"=._o." ,-"""-._ ". |
|___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________
| |o`"=._` , "` `; .". , "-._"-._; ; |
_________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
| | |o; `"-.o`"=._`` '` " ,__.--o; |
|___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____
/______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_
____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#Write your code below this line 👇
print("You\'re walking along the road.")
print("Soon, you have encountered two paths.")
choice1 = input("Where do you want to go? (left / right) ").lower()
if choice1 == "right":
print("After a while, you can see a huge, abandoned mansion.")
choice2 = input("You entered the house through the (door / window) ").lower()
if choice2 == "window":
print("The house is really quite.")
choice3 = input("You decide to search (basement / library / upstair) ").lower()
if choice3 == "basement":
print("You are attacked by a starved beast. [Game over]")
elif choice3 == "library":
print("Congratulation! You found a treasure chest [Game clear]")
else:
print("You slipped on the stairs and fell down [Game over]")
else:
print("As soon as you open the door, you triggered a trap. [Game over]")
else:
print("There was a group of robbers. [Game over]")