TIL | 파이썬 제어문

sik2·2021년 3월 30일
1

Python

목록 보기
3/5

파이썬의 제어문에 대해서 알아보자

비교연산자

조건문

if ~ else 문

  • 형식
if 조건:
   맞을경우 실행
else:
   조건이 맞지않을 경우 실행
  • if ~ else문을 활용한 함수 예시
def plus(a, b):
    if type(b) is int or type(b) is float:
    	return a+b
    else:
    	return None
	
print(plus(12, 1.2))

elif 문

  • 형식
if 조건:
   맞을경우 실행
elif 조건:
   elif 조건이 맞으면 실행
else:
   모든 조건이 맞지않을 경우 실행
  • elif 문을 활용한 함수 예시
def age_check(age):
   print(f"you are {age}")
   
   if age < 18:
      print("you can't drink")
   elif age == 18 or 19:
      print("you are new to this!")
   elif age>20 and age 
      print("you are still kind of young")
   else:
      print("enjoy your drink")

age_check(18)

반복문

for in

  • 형식
  • data에 list, tuple, string 자료형이 올 수 있다.
  • item에 해당 data value를 순차적으로 할당한다.
   for item in data:
      실행문
  • for in 문을 활용한 예시 코드
days = ("Mon", "Tue", "Wed", "Thu", "Fri")

for day in days: 
print(day)

while break, continue

  • 형식
  • data 값을 계속 반복한다.
  • continue 는 계속해서 다음행을 실행한다.
  • break는 해당 행에서 멈추고 반복문에서 빠져나온다.
  • 특정 조건에서 break 시켜 반복문에서 빠져나오지 않으면 무한루프에 걸릴 수 있다.
   while 조건:
      조건문: 
      continue
      조건문:
      break
  • while continue를 활용한 예시코드
   data = 10
   while data > 0:
      if data % 2 == 1: 
         print(data)
         continue
  • while break를 활용한 예시코드
   data = 10
   while data:
      if data <= 2:
      	 print(data)
         break
  • while 키워드에서 에서 조건을 줄 수 있다.
   data = 1
   while data < 10:
      data++
      print(data)

cf) 파이썬에는 switch 문이 없다.

참고자료

https://nomadcoders.co/python-for-beginners
https://docs.python.org/3/library/stdtypes.html#comparisons
https://docs.python.org/3/reference/compound_stmts.html

profile
기록

0개의 댓글