CH 05 Conditional Statement

Huisu·2021년 12월 1일
0

Python

목록 보기
5/17
post-thumbnail

Conditional Statement

if Statement

  • 조건문
  • if <condition>: <block> 형식
  • condition이 True일 때만 block 실행
  • condition은 boolean 값을 반환해 주는 문장
  • if <condition>: 후 들여쓰기 된 부분만 block이며 들여쓰기가 되지 않은 부분은 if 바깥 문장
  ph = float(input("Enter the pH level:"))
  
  if (ph < 7.0):
    	print (ph, "is acidic.")
  if (pg > 7.0):
  	print(ph, "is basic.")
  

else Statement

  • if 구문 후에 사용
  • else 단독 사용 불가능
  • if 구문이 False일 때 실행해야 할 내용 기입
  ph = float(input("Enter the pH level:")
  
  if (ph < 7.0):
  	print(ph, "is acidic.")
  else:
    	print(ph, "is basic.")

elif Statement

  • if 구문 후에 사용
  • elif 단독 사용 불가능
  • if 구문이 False일 때 만약 elif 조건이 True라면 실행해야 할 내용 기입
  • elif 여러 개 사용 가능
  ph = float(input("Enter the pH level:")
  
  if (ph < 7.0):
  	print(ph, "is acidic.")
  elif (ph > 7.0):
    	print(ph, "is basic.")

Nested if Statements

  • if, elif, else 구문을 중첩해서 사용 가능
  • 조건이 중첩되어 있을 때는 and 관계
  ph = float(input("Enter the pH level:")
  
  if (0 <= ph <= 14.0):
  	if (ph < 7.0):
    		print(ph, "is acidic.")
    	elif (ph > 7.0):
  		print(ph, "is basic.")
    	else:
  		print(ph, "is neutral")
   else:
  	print("pH value has to be number between 0 and 14")

0개의 댓글