Saltar al contenido principal

Condicionales y Bucles

Sentencias Condicionales (sentencias if)

Sentencia if básica

age = 20

if age >= 18:
print("성인입니다")

# 출력: 성인입니다

Sentencia if-else

age = 15

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

# 출력: 미성년자입니다

Sentencia if-elif-else

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}") # 학점: B

Sentencia if anidada

age = 20
has_license = True

if age >= 18:
if has_license:
print("운전 가능합니다")
else:
print("면허를 취득하세요")
else:
print("성인이 되어야 합니다")

Expresión Condicional (Operador Ternario)

# if-else en una línea
age = 20
status = "성인" if age >= 18 else "미성년자"
print(status) # 성인

# Expresiones condicionales anidadas
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade) # B

# Ejemplo práctico
numbers = [1, -2, 3, -4, 5]
positive = [n if n > 0 else 0 for n in numbers]
print(positive) # [1, 0, 3, 0, 5]

Combinar múltiples condiciones

age = 25
income = 3000

# Operador and
if age >= 18 and income >= 2000:
print("대출 가능")

# Operador or
if age < 18 or age >= 65:
print("할인 대상")

# Operador not
is_weekend = False
if not is_weekend:
print("평일입니다")

# Condiciones complejas
score = 85
attendance = 0.9

if (score >= 80 and attendance >= 0.8) or score >= 95:
print("합격")

Bucles (bucle for)

Bucle for básico

# Iterar sobre lista
fruits = ["사과", "바나나", "체리"]
for fruit in fruits:
print(fruit)

# Iterar sobre cadena
for char in "Python":
print(char)

# Usando range
for i in range(5):
print(i) # 0, 1, 2, 3, 4

for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5

for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8

Índice y valor con enumerate

fruits = ["사과", "바나나", "체리"]

for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: 사과
# 1: 바나나
# 2: 체리

# Especificar índice inicial
for index, fruit in enumerate(fruits, 1):
print(f"{index}. {fruit}")
# 1. 사과
# 2. 바나나
# 3. 체리

Iterar múltiples secuencias simultáneamente con zip

names = ["홍길동", "김철수", "이영희"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
print(f"{name}: {score}점")
# 홍길동: 85점
# 김철수: 92점
# 이영희: 78점

# Diferentes longitudes (se detiene en la más corta)
numbers = [1, 2, 3, 4, 5]
letters = ['a', 'b', 'c']

for num, letter in zip(numbers, letters):
print(num, letter)
# 1 a
# 2 b
# 3 c

Iterar sobre diccionario

person = {"name": "홍길동", "age": 25, "city": "서울"}

# Iterar sobre claves
for key in person:
print(key)

# Iterar sobre valores
for value in person.values():
print(value)

# Iterar sobre pares clave-valor
for key, value in person.items():
print(f"{key}: {value}")

Bucles anidados

# Tabla de multiplicar
for i in range(2, 10):
for j in range(1, 10):
print(f"{i} x {j} = {i*j}")
print() # 단 사이 빈 줄

# Lista 2D
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
for value in row:
print(value, end=" ")
print() # 줄바꿈

Bucles (bucle while)

Bucle while básico

# Cuenta regresiva
count = 5
while count > 0:
print(count)
count -= 1
print("발사!")

# Hasta que se cumpla la condición
number = 1
while number < 100:
number *= 2
print(number) # 128

Bucle infinito

# Repetir entrada del usuario
while True:
answer = input("계속하시겠습니까? (y/n): ")
if answer.lower() == 'n':
break
print("계속합니다...")

print("종료")

while-else

# else se ejecuta cuando la condición se vuelve False (terminación normal)
count = 0
while count < 3:
print(count)
count += 1
else:
print("정상 종료")

# else no se ejecuta cuando se termina con break
count = 0
while count < 10:
if count == 3:
break
count += 1
else:
print("이 부분은 실행 안 됨")

Control de Bucles

break - Salir del bucle

# Salir cuando se encuentra el valor deseado
numbers = [1, 3, 5, 7, 9, 2, 4, 6]

for num in numbers:
if num % 2 == 0:
print(f"첫 번째 짝수: {num}")
break

# break en bucles anidados
found = False
for i in range(10):
for j in range(10):
if i * j > 50:
found = True
break
if found:
break

continue - Saltar a la siguiente iteración

# Imprimir solo números impares
for i in range(1, 11):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9

# Saltar valores específicos
words = ["apple", "banana", "", "cherry", ""]
for word in words:
if not word:
continue
print(word.upper())

pass - No hacer nada

# Código a implementar más tarde
for i in range(5):
if i == 2:
pass # TODO: 나중에 구현
else:
print(i)

# Clase o función vacía
class MyClass:
pass # 일단 뼈대만

def my_function():
pass # 나중에 구현

Ejemplos Prácticos

Verificar número primo

def is_prime(n):
"""소수 판별"""
if n < 2:
return False

for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

# 100 이하 소수 출력
print("100 이하 소수:")
for num in range(2, 101):
if is_prime(num):
print(num, end=" ")

Máximo Común Divisor (MCD)

def gcd(a, b):
"""유클리드 호제법"""
while b != 0:
a, b = b, a % b
return a

print(gcd(48, 18)) # 6
print(gcd(100, 75)) # 25

Secuencia de Fibonacci

def fibonacci(n):
"""n번째 피보나치 수"""
if n <= 1:
return n

a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b

# 처음 10개 출력
print("피보나치 수열:")
for i in range(10):
print(fibonacci(i), end=" ")

Juego de adivinar números

import random

def guessing_game():
"""숫자 맞추기 게임"""
answer = random.randint(1, 100)
attempts = 0
max_attempts = 10

print("1부터 100 사이의 숫자를 맞춰보세요!")
print(f"기회는 {max_attempts}번입니다.")

while attempts < max_attempts:
try:
guess = int(input(f"\n남은 기회 {max_attempts - attempts}번 > "))

attempts += 1

if guess < answer:
print("UP! 더 큰 숫자입니다.")
elif guess > answer:
print("DOWN! 더 작은 숫자입니다.")
else:
print(f"정답! {attempts}번 만에 맞췄습니다!")
return True

except ValueError:
print("숫자를 입력하세요!")
continue

print(f"\n실패! 정답은 {answer}였습니다.")
return False

# 게임 실행
guessing_game()

Imprimir calendario

def print_calendar(year, month):
"""간단한 달력 출력"""
import calendar

# 해당 월의 달력
cal = calendar.monthcalendar(year, month)

# 헤더
print(f"\n{'':^20}")
print(f"{year}{month}월".center(20))
print(f"{'':^20}")
print("월 화 수 목 금 토 일")
print("-" * 22)

# 날짜 출력
for week in cal:
for day in week:
if day == 0:
print(" ", end=" ")
else:
print(f"{day:2d} ", end=" ")
print()

print_calendar(2024, 12)

Calculadora simple

def calculator():
"""사칙연산 계산기"""
print("=== 계산기 ===")
print("종료하려면 'q'를 입력하세요")

while True:
# 수식 입력
expression = input("\n수식 입력 (예: 2 + 3): ")

if expression.lower() == 'q':
print("종료합니다")
break

try:
# 수식 파싱
parts = expression.split()
if len(parts) != 3:
print("형식: 숫자 연산자 숫자")
continue

num1 = float(parts[0])
operator = parts[1]
num2 = float(parts[2])

# 계산
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("0으로 나눌 수 없습니다")
continue
result = num1 / num2
else:
print("지원하지 않는 연산자입니다")
continue

print(f"결과: {result}")

except ValueError:
print("올바른 숫자를 입력하세요")
except Exception as e:
print(f"오류: {e}")

# calculator() # 주석 해제하여 실행

Patrones de estrellas

def print_patterns():
"""다양한 별 패턴"""
n = 5

# 패턴 1: 삼각형
print("패턴 1:")
for i in range(1, n + 1):
print("*" * i)

print()

# 패턴 2: 역삼각형
print("패턴 2:")
for i in range(n, 0, -1):
print("*" * i)

print()

# 패턴 3: 피라미드
print("패턴 3:")
for i in range(1, n + 1):
spaces = " " * (n - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)

print()

# 패턴 4: 다이아몬드
print("패턴 4:")
# 상단
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
# 하단
for i in range(n - 1, 0, -1):
print(" " * (n - i) + "*" * (2 * i - 1))

print_patterns()

Procesamiento de calificaciones

def process_grades():
"""성적 입력 및 통계"""
scores = []

print("=== 성적 입력 ===")
print("종료하려면 -1을 입력하세요")

while True:
try:
score = int(input("점수 입력: "))

if score == -1:
break

if score < 0 or score > 100:
print("0~100 사이의 점수를 입력하세요")
continue

scores.append(score)

except ValueError:
print("숫자를 입력하세요")

if not scores:
print("입력된 점수가 없습니다")
return

# 통계 계산
total = sum(scores)
average = total / len(scores)
highest = max(scores)
lowest = min(scores)

# 학점 분포
grade_count = {"A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
for score in scores:
if score >= 90:
grade_count["A"] += 1
elif score >= 80:
grade_count["B"] += 1
elif score >= 70:
grade_count["C"] += 1
elif score >= 60:
grade_count["D"] += 1
else:
grade_count["F"] += 1

# 결과 출력
print("\n=== 성적 통계 ===")
print(f"인원: {len(scores)}명")
print(f"총점: {total}점")
print(f"평균: {average:.1f}점")
print(f"최고점: {highest}점")
print(f"최저점: {lowest}점")

print("\n=== 학점 분포 ===")
for grade, count in grade_count.items():
if count > 0:
print(f"{grade}: {count}명")

# process_grades() # 주석 해제하여 실행

Preguntas Frecuentes

Q1. ¿Debo usar for o while?

R: Elija según la situación

# for: Cuando conoce el número de iteraciones
for i in range(10):
print(i)

# while: Hasta que se cumpla una condición
while user_input != "quit":
user_input = input("명령: ")

# Elección práctica
# - Iterar colecciones: for
# - Iteración basada en condiciones: while
# - Bucle infinito: while True

Q2. range vs enumerate, ¿cuál usar?

R: Use enumerate si necesita tanto el índice como el valor

fruits = ["사과", "바나나", "체리"]

# ❌ No recomendado
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")

# ✅ Recomendado
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")

Q3. ¿Cuál es la diferencia entre break y return?

R: break solo sale del bucle, return sale de la función

def find_number(numbers, target):
for num in numbers:
if num == target:
return num # 함수 종료
return None

def process_data(data):
for item in data:
if item < 0:
break # 반복문만 종료
print(item)
print("함수는 계속 실행") # 이 부분은 실행됨

Q4. ¿Cómo prevengo los bucles infinitos?

R: Haga claras las condiciones y las condiciones de salida

# ❌ Bucle infinito peligroso
count = 0
while count < 10:
print(count)
# count를 증가시키지 않음!

# ✅ Bucle seguro
count = 0
max_iterations = 1000 # 안전장치
while count < 10 and max_iterations > 0:
print(count)
count += 1
max_iterations -= 1

# ✅ Condición de salida clara
while True:
user_input = input("입력 (q=종료): ")
if user_input == 'q':
break
process(user_input)

Próximos Pasos

¡Ha dominado el control de flujo del programa!

Puntos clave:
✅ Ramificación condicional con if-elif-else
✅ Iterar colecciones con for
✅ Iteración basada en condiciones con while
✅ Control con break, continue, pass
✅ Ejemplos prácticos (juegos, calculadora, etc.)

Próximo paso: ¡Aprenda a hacer el código reutilizable en Funciones!