[Python] if 문, for 문, while 문, continue와 break, 한 줄 for문

룽지·2021년 8월 23일
0

Python

목록 보기
8/10
post-thumbnail

1. if 문

# input은 문자열만 입력 가능
weather = input("오늘 날씨는 어때요? ")
if weather == "비" or weather == "눈":
    print("우산을 챙기세요")
elif weather == "미세먼지":
    print("마스크를 챙기세요")
else:
    print("준비물 필요 없어요")

# 숫자를 입력할때 input 앞에 int 추가
temp = int(input("기온은 어때요? "))
if 30 <= temp:
    print("너무 더워요. 나가지 마세요")
elif 10 <= temp and temp < 30:
    print("괜찮은 날씨예요")
elif 0 <= temp < 10:
    print("외투를 챙기세요")
else:
    print("너무 추워요. 나가지 마세요.")
    
>>>
오늘 날씨는 어때요? 비
우산을 챙기세요
기온은 어때요? 30
너무 더워요. 나가지 마세요

2. for 문

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

starbucks = ["아이언맨", "토르", "아이엠 그루트"]
for customer in starbucks:
    print("{0}, 커피가 주문되었습니다.".format(customer))
    
>>>
아이언맨, 커피가 주문되었습니다.
토르, 커피가 주문되었습니다.
아이엠 그루트, 커피가 주문되었습니다.

3. while 문

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

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

customer = "토르"
person = "Unknown"

while person != customer:
    print("{0}, 커피가 준비되었습니다.".format(customer))
    person = input("이름이 어떻게 되세요? ")
    
>>>
토르, 커피가 준비되었습니다.    
이름이 어떻게 되세요? 아이언맨
토르, 커피가 준비되었습니다.    
이름이 어떻게 되세요? 토르

4. 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))
    
>>>
1, 책을 읽어봐
3, 책을 읽어봐
4, 책을 읽어봐
6, 책을 읽어봐
오늘 수업 여기까지. 7는 교무실로 따라와

5. 한 줄 for문

# 출석번호가 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102, 103, 104
students = [1,2,3,4,5]
students = [i+100 for i in students]
print(students)

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

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

>>>
[101, 102, 103, 104, 105]       
[8, 4, 10]
['IRON MAN', 'THOR', 'I AM GROOT']



📒 참고 자료
https://www.youtube.com/watch?v=kWiCuklohdY

0개의 댓글