Programming/Python

Python 조건문과 반복문

Isaac S. Lee 2023. 6. 10. 16:23

조건문(Conditional Statements)

파이썬에서 조건문은 주어진 조건에 따라 프로그램의 특정 부분을 실행하거나 건너뛸 수 있는 구문이다.

파이썬에서는 if, elif (else if), else 조건문을 제공한다.

if 문

x = 10

if x > 0:
    print("x는 양수입니다.")

 

if - elif - else 문

x = 0

if x > 0:
    print("x는 양수입니다.")
elif x < 0:
    print("x는 음수입니다.")
else:
    print("x는 0입니다.")

 

조건문의 활용

중첩 조건문

중첩 조건문은 한 조건문 안에 다른 조건문을 포함시키는 것을 의미하며,이를 통해 복잡한 조건 로직을 구현할 수 있다.

x = 10
y = 5

if x > 0:
    if y > 0:
        print("x와 y는 양수입니다.")
    else:
        print("x는 양수이지만 y는 양수가 아닙니다.")
else:
    print("x는 양수가 아닙니다.")

 

삼항 연산자

삼항 연산자(conditional expression)는 조건문을 간단하게 표현하는 방법으로, 조건이 참일 때와 거짓일 때의 값을 간단히 반환한다.

x = 10
result = "양수" if x > 0 else "음수"
print(result) # 출력: 양수

 

반복문(Loop Statements)

반복문은 특정한 코드 블록을 반복적으로 실행하는 데 사용된다.

파이썬에서는 while과 for 반복문을 제공하며, break 문과 continue 문을 사용하여 특정 조건에서 반복을 중지하거나 건너뛸 수 있다.

while 반복문

while 반복문은 주어진 조건이 참인 동안 반복적으로 코드를 실행하며, 조건이 거짓이 되면 반복문을 빠져나온다.

count = 0

while count < 5:
    print(count)
    count += 1

 

for 반복문

for 반복문은 시퀀스(리스트, 튜플, 문자열 등)의 각 요소에 대해 반복적으로 코드를 실행한다.

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

 

break 문을 사용하여 중지

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)

 

continue 문을 사용하여 건너뛰기

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    if fruit == "banana":
        continue
    print(fruit)

 

반복문의 활용

range() 함수

range() 함수는 반복문에서 특정 범위의 숫자를 생성하는 데 사용된다.

일반적으로 for 반복문과 함께 사용되며, 반복 횟수를 제어하는 데 유용하다.

# 0부터 4까지 반복
for i in range(5):
    print(i)

# 1부터 10까지 홀수만 반복
for i in range(1, 11, 2):
    print(i)

 

enumerate() 함수

enumerate() 함수는 순회 가능한 객체(리스트, 튜플, 문자열 등)를 순회하면서 현재 요소의 인덱스와 값을 함께 반환하며, 이를 통해 인덱스와 값에 동시에 접근할 수 있다.

fruits = ["apple", "banana", "orange"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

 

+ 조건문과 반복문의 효율을 높이는 방법

함수로 작성

def calculate_average(scores):
    total = sum(scores)
    average = total / len(scores)
    return average

 

모듈로 분리하여 사용

# calculator.py
def add(a, b):
    return a + b

# main.py
import calculator
result = calculator.add(5, 3)
print(result) # 출력: 8

 

반복 대상의 효율적인 선택

fruits = ["apple", "banana", "orange"]
for i in range(len(fruits)):
    print(fruits[i])

 

중복된 작업 최소화

numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
    squared_numbers.append(number ** 2)
print(squared_numbers) # 출력: [1, 4, 9, 16, 25]

 

주석 활용

# 두 숫자를 더하는 코드
a = 5
b = 3
result = a + b
print(result) # 출력: 8