1. if
# #If
# if 조건:
# 실행 명령문
# elif 조건:
# 실행 명령문
# else:
# 실행 명령문
#weather = "맑음"
weather = input("오늘 날씨는 어때요?") # 값 입력 받으면 if문 실행
if weather == "비" or weather == "눈":
print("우산을 챙기세요")
elif weather == "미세먼지":
print("마스크를 챙기세요")
else:
print("준비물 필요 없어요.")
#--------------------------------------------------------------------------------
temp = int(input("기온은 어때요? "))
if 30 <= temp:
print("너무 더워요. 나가지 마세요")
elif 10 <= temp and temp < 30:
print("괜찮은 날씨에요")
elif 0 <= temp < 10: # and 생략 가능
print("외투를 챙기세요")
else:
print("너무 추워요. 나가지 마세요")
2. for
# for
#print("대기번호 : 1")
# for waiting_num in [0,1,2,3,4]:
# print("대기번호 : {0}".format(waiting_num))
# 순차적은 range()사용가능
for waiting_num in range(5): # 0,1,2,3,4
print("대기번호 : {0}".format(waiting_num))
for waiting_num in range(1,6): # 1부터 6 미만까지
print("대기번호 : {0}".format(waiting_num))
#----------------------------------------------------------------------------------
starbucks = ["A","B","C"]
for customer in starbucks:
print("{0}, 커피가 준비되었습니다.".format(customer))
3. While
# While
예제 1)
customer = "A"
index = 5
while index >= 1:
print("{0}, 커피가 준비 되었습니다. {1} 번 남았어요.".format(customer, index))
index -= 1
if index == 0:
print("커피는 폐기처분되었습니다.")
#----------------------------------------------------------------------------------
예제 2)
customer = "연정"
person = "Unknown"
while person != customer : # 조건 만족할 때까지 조건문 반복
print("{0}, 커피가 준비 되었습니다.".format(customer))
person = input("이름이 어떻게 되세요?") # 이름 입력받음
4. continue 와 break
# continue 와 break
no_book = [7] # 책 없다
absent = [2,5] # 2번 5번 결석
# 다른 친구에겐 책을 읽게 하자 = continue
for student in range(1,11): # 1~ 10
if student in absent:
continue
elif student in no_book:
print("오늘 수업 여기까지. {0}은 남아서 자습해라.".format(student))
break
print("{0}, 책을 읽어봐".format(student))
5. 한 줄 for
# 한 줄 for
# 출석번호 1,2,3,4 앞에 100을 붙이기로 함 -> 101, 102, 103, 104
students = [1,2,3,4,5]
print(students)
students = [i+100 for i in students] # students의 i를 불러와서 거기다 100 더함
print(students)
# 학생 이름을 길이로 변환
students = ["Katy", "Ariana", "Lizzo"]
students = [len(i) for i in students]
print(students)
# 학생 이름을 대문자로 변환
students = ["Katy", "Ariana", "Lizzo"]
students = [i.upper() for i in students]
print(students)
<Quiz 5>
# Quiz 5)
# 당신은 Tada 서비스를 이용하는 택시 기사님입니다.
# 50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램을 작성하시오.
# 조건 1 : 승객별 운행 소요 시간은 5분 ~ 50분 사이의 난수로 정해집니다.
# 조건 2 : 당신은 소요 시간 5분 ~ 15분 사이의 승객만 매칭해야 합니다.
# (출력문 예제)
# [O] 1번재 손님 (소요시간 : 15분) 선택이 되었다. 탑승 O
# [ ] 2번재 손님 (소요시간 : 50분) 조건 안맞음. 탑승 X
# [O] 3번재 손님 (소요시간 : 5분)
# . . .
# [ ] 50번재 손님 (소요시간 : 16분)
# 총 탑승 승객 : 2분 // 승객 수 구하기
from random import *
cnt = 0 # 총 탑승 승객 수
for i in range(1,51): # 1 ~ 50 승객 수
time = randrange(5,51)
if 5 <= time <= 15: # 5분 ~ 15분 이내의 손님, 탑승 승객 수 증가 처리
print("[O] {0}번째 손님 (소요시간 : {0}분)".format(i, time))
cnt += 1 # 매칭 되면 카운트 업
else:
print("[ ] {0}번째 손님 (소요시간 : {0}분)".format(i, time))
print("총 탑승 승객 : {0} 분".format(cnt))