목차

    프로그래밍언어/Python

    파이썬 - 흐름과 제어(조건문)

    멍토 2020. 1. 15.

    목차

      if문 : 어떤 조건을 만족하는 경우, 명령문을 수행하기 위해 사용

       

      파이썬 - 흐름과 제어(조건문)

       


      if문의 문법

      if 조건식 :
          명령문
          명령문
      #들여쓰기 필수

      if 문의 활용(예시)

      score = 80
      if score >= 60:
          print("%d 점" % score)
          print("합격입니다.")
      => 80 점
           합격입니다.

      if 문의 활용(예시2)

      score = 80
      result = "불합격입니다."
      if score >= 60:
          result = "합격입니다."
      print(result)
      => 합격입니다.
      #기본값을 불합격으로 설정후 60점 이상이라면 합격입니다. 라고 변경

      if ~else 문 : 어떤 조건을 만족하는 경우와 그렇지 않은 경우를 수행하고자 할 때 사용

      파이썬 - 흐름과 제어(조건문)

      if ~ else 문의 문법

      if 조건식 :
          명령문
          명령문
      else :
          명령문
          명령문

      if~else 예시

      scroe = 80
      if score >= 60 :
          print("합격입니다")
      else :
          print("불합격입니다")

      if~ elif~ else 문 : 2개 이상의 다중조건을 처리하고자 할 때 사용

      파이썬 - 흐름과 제어(조건문)

      if 조건식 :
          명령문
      elif 조건식 : 
          명령문
      elif 조건식 :
          명령문
      else :
          명령문

       

      if~elif~else 예제

      score = 70
      if score >=90:
          grade = "A"
      elif score >= 80:
          grade = "B"
      elif score >=70:
          grade = "C"
      elif score >=60:
          grade = "D"
      else :
          grade = "F"
      print("%d 점은 %s 등급 입니다." % (score, grade) )
      => 70 점은 C 등급 입니다.
      #score = int(input("점수를 입력하세요:"))  로 바꾸면 입력받은 점수로 사용이 가능하다.

      if문을 이용한 간단한 계산기 만들기

      operand1, operator, operand2 = 0, "", 0
      operand1 = int(input("첫 번째 숫자를 입력하세요 : "))
      operator = input("연산자를 입력하세요(+, -, *, /) : ")
      operand2 = int(input("두 분째 숫자를 입력하세요 : "))
      if operator == "+" :
          print("%d + %d = %d" % (operand1 , operand2, operand1 + operand2) )
      elif operator == "-" :
          print("%d - %d = %d" % (operand1 , operand2, operand1 - operand2) )
      elif operator == "*" :
          print("%d * %d = %d" % (operand1 , operand2, operand1 * operand2) )
      elif operator == "/" :
          print("%d / %d = %.2f" % (operand1 , operand2, operand1 / operand2) )
      else :
          print("'%s'는 본 프로그램에서 지원하지 않는 연산자입니다" % operator)

       

      댓글