본문 바로가기

Backend/Python

제어문

if

weather = input("오늘 날씨는 어때요? ")
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 and temp < 10:
    print("외투를 챙기세요")
else:
    print("너무 추워요. 나가지 마세요")

for

for waiting_num in range(6):  # 0, 1, 2, 3, 4, 5
    print("대기번호 : {0}".format(waiting_num))

starbucks = ["아이언맨", "토르", "그루트"]
for customer in starbucks:
    print("{0}, 커피가 준비되었습니다.".format(customer))
    
<한줄 for문>
# 출석 번호가 1 2 3 4, 앞에 100을 붙이기로 함
students = [1, 2, 3, 4, 5]
print(students)
students = [i+100 for i in students]
print(students)

# 학생이름을 길이로 변환
students = ["Iron man", "Thor", "Groot"]
students = [len(i) for i in students]
print(students)

# 학생이름을 대문자로 변화
students = ["Iron man", "Thor", "Groot"]
students = [i.upper() for i in students]
print(students)

while

# 횟수차감
customer = "토르"
index = 5
while index >= 1:
    print("{0}, 커피가 준비 되었습니다. {1} 번 남았어요.".format(customer, index))
    index -= 1
    if index == 0:
        print("커피는 폐기처분되었습니다.")

# 무한루프 
customer = "아이언맨"
while True:
    print("{0},커피가 준비 되었습니다. 호출 {1} 회".format(customer, index)) 
    index += 1  

# while문 종료(루프 탈출)
customer = "토르"
person = "Unknown"
while person != customer:
    print("{0}, 커피가 준비되었습니다.".format(customer)) 
    person = input("이름이 어떻게 되세요?")

continue & break

absent = [2, 5]  # 결석
no_book = [7]  # 책을 깜박함
for student in range(1, 11):  # 1,2,3,4,5,6,7,8,9,10
    if student in absent:
        continue  # 빼고 다음 반복을 진행
    elif student in no_book:
        print("오늘 수업 여기까지. {0}는 교무실로 따라와".format(student))
        break  # 반복문 탈출
    print("{0}, 책을 읽어봐".format(student))

퀴즈

# 택시 기사
# 50명의 승객과 매칭 기회. 총 탑승 승객 수 구하기
# 승객별 운행 소요 시간은 5분~50분 사이의 난수(랜덤)
# 소요시간 5분~15분 사이의 승객만 매칭해야함
# (출력 예제)
# [O] 1번째 손님 (소요시간 : 15분)
# [ ] 2번째 손님 (소요시간 : 50분)
# [O] 3번째 손님 (소요시간 : 5분)
# ...
# [ ] 50번째 손님 (소요시간 : 16분)
# 총 탑승 승객 : 2 분
from random import*

cnt = 0  # 총 탑승 승객 수
for i in range(1, 51):
    time = randrange(5, 51)
    if 5 <= time and time <= 15:
        print("[O] {0}번째 손님 (소요시간 : {1}분)".format(i, time))
        cnt += 1  # 탑승 승객 수 증가 처리
    else:
        print("[ ] {0}번째 손님 (소요시간 : {1}분)".format(i, time))

print("총 탑승 승객 수 : {0} 분".format(cnt))

'Backend > Python' 카테고리의 다른 글

입출력  (0) 2022.02.01
함수  (0) 2022.02.01
자료구조  (0) 2022.01.31
문자열 처리  (0) 2022.01.29
랜덤함수  (0) 2022.01.29