본문 바로가기

python/코딩자율학습단

나도코딩의 파이썬 입문_6장

 

나도코딩의 파이썬 입문_코딩자율학습단

6장_제어문

 

 

6.1 조건에 따라 분기하기: 조건문

# 6장_제어문

# if : 조건이 하나일 때
# if 조건:
#	실행 명령문

weather = input("오늘 날씨는 어때요? ") # input: 사용자의 입력 받음
if weather == "비" or weather == "눈":
	print("우산을 챙기세요")
elif weather == "미세먼지":
	print("마스크를 챙기세요")
else:
	print("준비물 필요없어요")
    
temp = int(input("기온은 어때요? "))
if temp >= 30:
	print("너무 더워요. 나가지 마세요")
elif 10 <= temp < 30:
	print("괜찮은 날씨예요")
elif 0 <= temp and temp < 10:
	print("외투를 챙기세요")
else:
	print("너무 추워요. 나가지 마세요")

 

 

6.2 같은 일 반복하기: 반복문 

* for 문

  for 변수 in 반복 대상:

           실행할 명령1

           실행할 명령2

            ...

# 반복문 for
# print("대기번호 : 1")
# print("대기번호 : 2")
# print("대기번호 : 3")
# print("대기번호 : 4")

for waiting_no in [1, 2, 3, 4, 5]:
	print("대기번호 : {0}".format(waiting_no))
    
for waiting_no in range(1, 6) # 1부터 6직전까지(1, 2, 3, 4, 5)
    print("대기번호 : {0}".format(waiting_no))
    
starbucks = ["아이언맨", "토르", "스파이더맨"] # 리스트 생성
for customer in starbucks:
	print("{0}, 커피가 준비되었습니다.".format(customer))

 

* while 문

  while 조건:

           실행할 명령1

           실행할 명령2

           ...

# while(조건)
customer = "토르"
index = 5
while index >= 1: # 부른 횟수가 1회 이상일 떄만 실행
	print("{0}, 커피가 준비되었습니다. {1}번 남았어요.".format(customer, index))
    index -= 1 # 횟수 1회 차감
    if index == 0 # 5번 모두 불렀을 때
    print("커피가 폐기처분 되었습니다.")
    
# 무한루프 => ctrl + c 종료
customer = "아이언맨"
index = 1
while True:
	print("{0}, 커피가 준비되었습니다. 호출{1}회".format(customer, index))
    index += 1
    
# input 이름 입력 받기
customer = "토르"
person = "Unknown"

while person != customer:
	print("{0}, 커피가 준비되었습니다.".format(customer))
    person = input("이름이 어떻게 되세요?")
# customer 입력이 토르가 될 때까지 while문 반복, 토르가 나오면 반복문 탈출

 

* continue & break

# continue & break
absent = [2, 5] # 결석한 학생 출석번호
no_book = [7] # 책을 깜빡한 학생 출석번호

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))

 

* 한줄 for문

   동작 for 변수 in 반복 대상

# 한 줄 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]
pritn(students)
# 변수는 i 아닌 임의의 이름 사용 가능 

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

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

 

 

# 실습 문제

# 실습 문제
# 손님이 총 50명일 때, 조건을 만족하는 총 탑승객 수 구하기
# 조건) 손님별 운행 소요시간 :  5 ~ 50분에서 난수
# 운행 소요시간 5 ~ 15분인 손님만 매칭, 매칭되면 [O], 매칭되지 않으면 [X] 표시

from random import *
cnt = 0 # 총 탑승객 수
for i in range(1, 51): # 손님 수 1 ~ 50
	time = randrange(5, 51) # 소요시간 5 ~ 50분 난수
    if 5 <= time <= 15: # 손님 중 5 ~ 15분만 매칭, 탑승 승객 수 증가 처리
    	print("[O] {0}번째 손님 (소요시간 : {1}분)".format(i, time))
        cnt += 1 # 매칭 성공, cnt(탑승객수) 증가
    else: # 매칭 실패, cnt(탑승객수) 그대로
    	print("[ ] {0}번쟤 손님 (소요시간 : {1}분)".format(i, time))

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

 

 

# 셀프 체크

# 셀프 체크
# 편의점에서 2+1 이벤트 진행, 구매 상품 수에 따라 가격을 계산하는 프로그램
# 조건) 상품 1개 가격 1000원, 고객은 3, 6, 9...처럼 항상 3의 배수에 해당하는 상품 구매
# 상품은 각각 스캔하고 한 상품 스캔할 때마다 '2+1 상품입니다' 출력

price = 1000 # 상품 가격
goods = 3 # 구매 상품 수 
total = 0 # 총 가격

for i in range(1, goods+1) # 구매 상품 수:3 => 1 ~ 3까지
	print("2+1 상품입니다.")
    if i % 3 == 0: # 3의 배수인 경우 가격을 더하지 않음(2+1)
		continue
    total += price

print("총 가격은 " + str(total) + "원입니다.")

 

 

 


 

 

 

# 실습 결과