파이썬 조건문(if else)
조건문(if else)는 프로그래밍 언어에서 중요한 역할을 합니다.
조건문은 특정 조건을 통해 코드 블럭을 실행할 수 있습니다.
# if 문
if 문은 특정 조건을 테스트하는 데 사용됩니다.
조건이 true이면 코드 블록 (if-block)이 실행됩니다.
# if-else 문
if-else 문은 if 문과 유사하지만, 검사 할 조건의 잘못된 경우에 대한 코드 블록도 제공한다는 점을 제외하고는 if 문과 유사합니다.
if 문에 제공된 조건이 false이면 else 문이 실행됩니다.
# 중첩 된 if 문
if 문을 사용하면 중첩 된 if 문을 사용할 수 있습니다. 외부 if 문 안에 else 문이 있습니다.
if 문의 구문은 다음과 같습니다.
if expression:
statement
# if문 예시
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
# if-else 문
if-else 문은 조건의 잘못된 경우에 실행되는 if 문과 결합 된 else 블록을 제공합니다.
조건이 true이면 if-block이 실행됩니다. 그렇지 않으면 else-block이 실행됩니다.
if-else 문의 구문은 다음과 같습니다.
if condition:
#block of statements
else:
#another block of statements (else-block)
# if-else 문 예시
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
# elif 문
elif 문을 사용하면 여러 조건을 확인하고 실제 조건에 따라 특정 문장 블록을 실행할 수 있습니다.
필요에 따라 프로그램에 여러 가지 elif 선언문을 가질 수 있습니다.
그러나 elif를 사용하는 것은 선택 사항입니다.
elif 문의 구문은 다음과 같습니다.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
# elif 문 예시
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");