파이썬의 Control flow인 if, for, while문에 대해 배운 것을 작성해보려 한다. 그 외 한 줄 표기법 또한 정리하였다.
기본 형태
if 조건문1: # 조건문1이 참이라면 실행문1 실행 실행문1 elif 조건문2: # 조건문2가 참이라면 실행문2 실행 실행문2 else: # 조건문1,2가 거짓이라면 실행문3 실행 실행문3
or
나and
같은 논리 연산도 사용이 가능하다.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 < 10: print("외투를 챙기세요.") else: print("너무 추워요. 나가지 마세요.")
기본 형태
for 변수선언 in 객체: 실행문
for waiting_no in range(1, 6): print("대기번호 : {0}".format(waiting_no)) # 1~5, 총 5번 실행 starbucks = ["아이언맨", "토르", "아이엠 그루트"] for customer in starbucks: print("{0}, 커피가 준비되었습니다.".format(customer)) # 총 4번 실행
기본 형태
while 조건문: 실행문
조건문이 거짓일 경우
while
문에서 벗어난다.customer = "토르" index = 5 while index >= 1: print("{0}, 커피가 준비 되었습니다. {1} 번 남았어요.".format(customer, index)) index -= 1 if index == 0: print("커피는 폐기처분되었습니다.") customer = "토르" person = "Unknown" while person != customer: print("{0}, 커피가 준비 되었습니다.".format(customer)) person = input("이름이 어떻게 되세요? ")
조건문이 변하지 않는다면 무한루프에 빠지게된다.
벗어나는 방법은control
+c
누르면된다.customer = "아이언맨" index = 1 while True: # 무한루프 print("{0}, 커피가 준비 되었습니다. 호출 {1} 회".format(customer, index)) index += 1
Control flow 안에서 조건에 따라 플로우를 벗어날지, 무시하고 넘어갈지를 결정 할 수 있는데, continue
break
를 사용한다.
absent = [2, 5] # 결석 no_book = [7] # 책 미지참 for student in range(1, 11): if student in absent: continue if student in no_book: print("오늘 수업 여기까지. {0}는 교무실로 따라와.".format(student)) break print("{0}, 책을 읽어봐".format(student))
continue
조건문에 따라 다음으로 넘어가고 싶을 때 사용한다.
break
조건문에 따라 실행문을 종료하고 싶을 때 사용한다.
기본 형태
실행문1 if 조건문 else 실행문2 # 조건문이 참이라면 실행문1 실행, 거짓이라면 실행문2 실행
color = 4 print(True if color <= 5 else False) # True
Javascript의
map()
메소드와filter()
메소드와 유사하다.(지극히 개인적인 생각..)
기본 형태변수 = [리턴값 for 변수선언 in 객체]
students = [1,2,3,4,5] print(students) 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)
기본 형태1
변수 = [리턴값 for 변수선언 in 객체 if 조건문]
nums = [1,2,3,4,5,6,7,8,9,10] even_nums = [i for i in nums if i%2 == 0] print(even_nums) # [2, 4, 6, 8, 10]
기본 형태2
변수 = [실행문1 if 조건문 else 실행문2 for 변수선언 in 객체] # 조건문이 참이면 실행문1, 거짓이면 실행문2
is_even_nums = [True if i%2 == 0 else False for i in nums] print(is_even_nums) # [False, True, False, True, False, True, False, True, False, True]