본문 바로가기
개발&프로그래밍

[Python] if문과 조건문

by 재아군 2024. 11. 26.

[Python] if문과 조건문 

조건문은 프로그래밍의 기본 구성 요소로, 프로그램의 흐름을 제어하는 핵심 요소다. Python의 조건문 사용법을 기초부터 심화까지 알아보자.

 

 

조건문 기초

기본 if문 구조

# 단순 if문
temperature = 30
if temperature > 28:
    print("에어컨을 켭니다")

# if-else문
age = 20
if age >= 18:
    print("성인입니다")
else:
    print("미성년자입니다")

# 중첩 if문
score = 85
if score >= 60:
    print("합격입니다")
    if score >= 90:
        print("우수한 성적입니다")

 

비교 연산자

# 다양한 비교 연산자 활용
x = 10
y = 20

if x == y:    # 같음
    print("x와 y는 같습니다")
if x != y:    # 다름
    print("x와 y는 다릅니다")
if x < y:     # 작음
    print("x는 y보다 작습니다")
if x <= y:    # 작거나 같음
    print("x는 y보다 작거나 같습니다")

 

논리 연산자

 

and, or, not 활용

# and 연산자
username = "python"
password = "1234"
if username == "python" and password == "1234":
    print("로그인 성공")

# or 연산자
holiday = True
weekend = False
if holiday or weekend:
    print("오늘은 쉬는 날입니다")

# not 연산자
is_logged_in = False
if not is_logged_in:
    print("로그인이 필요합니다")

 

복합 조건

age = 25
income = 3000000
credit_score = 750

# 여러 조건 조합
if age >= 20 and (income >= 2500000 or credit_score >= 700):
    print("대출 자격이 있습니다")

 

elif 활용

다중 조건 처리

# 성적 등급 판정
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"학점: {grade}")

# 요일별 일정
day = "월요일"
if day == "월요일":
    schedule = "회의"
elif day == "화요일":
    schedule = "프로젝트 작업"
elif day == "수요일":
    schedule = "발표"
else:
    schedule = "자유 일정"

 

조건부 표현식

 

기본 문법

# 일반적인 if-else문
status = ""
if age >= 18:
    status = "성인"
else:
    status = "미성년자"

# 조건부 표현식 사용
status = "성인" if age >= 18 else "미성년자"

 

실전 활용

# 절대값 계산
def get_absolute(number):
    return number if number >= 0 else -number

# 삼항 연산자 중첩
def get_grade(score):
    return "A" if score >= 90 else "B" if score >= 80 else "C"

# 리스트 필터링
numbers = [1, -2, 3, -4, 5]
positive_nums = [n for n in numbers if n > 0]

 

실전 예제

 

사용자 입력 검증

def validate_input(value):
    # 입력값 검증
    if not value:
        return "값을 입력해주세요"
    elif not value.isdigit():
        return "숫자만 입력 가능합니다"
    elif int(value) < 0:
        return "양수를 입력해주세요"
    else:
        return "유효한 입력입니다"

 

상태 처리

def process_payment(amount, balance):
    if amount <= 0:
        return "잘못된 금액입니다"
    elif amount > balance:
        return "잔액이 부족합니다"
    else:
        balance -= amount
        return f"결제 완료 (잔액: {balance}원)"

 

데이터 분류

def categorize_number(num):
    if num == 0:
        return "zero"
    elif num % 2 == 0:
        return "even"
    else:
        return "odd"

numbers = [1, 2, 3, 4, 5, 0]
categories = [categorize_number(num) for num in numbers]

 

댓글