Skip to main content

Conditionals and Loops

Conditional Statements (if statements)โ€‹

Basic if statementโ€‹

age = 20

if age >= 18:
print("์„ฑ์ธ์ž…๋‹ˆ๋‹ค")

# ์ถœ๋ ฅ: ์„ฑ์ธ์ž…๋‹ˆ๋‹ค

if-else statementโ€‹

age = 15

if age >= 18:
print("์„ฑ์ธ์ž…๋‹ˆ๋‹ค")
else:
print("๋ฏธ์„ฑ๋…„์ž์ž…๋‹ˆ๋‹ค")

# ์ถœ๋ ฅ: ๋ฏธ์„ฑ๋…„์ž์ž…๋‹ˆ๋‹ค

if-elif-else statementโ€‹

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

Nested if statementโ€‹

age = 20
has_license = True

if age >= 18:
if has_license:
print("์šด์ „ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค")
else:
print("๋ฉดํ—ˆ๋ฅผ ์ทจ๋“ํ•˜์„ธ์š”")
else:
print("์„ฑ์ธ์ด ๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค")

Conditional Expression (Ternary Operator)โ€‹

# One-line if-else
age = 20
status = "์„ฑ์ธ" if age >= 18 else "๋ฏธ์„ฑ๋…„์ž"
print(status) # ์„ฑ์ธ

# Nested conditional expressions
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade) # B

# Practical example
numbers = [1, -2, 3, -4, 5]
positive = [n if n > 0 else 0 for n in numbers]
print(positive) # [1, 0, 3, 0, 5]

Combining multiple conditionsโ€‹

age = 25
income = 3000

# and operator
if age >= 18 and income >= 2000:
print("๋Œ€์ถœ ๊ฐ€๋Šฅ")

# or operator
if age < 18 or age >= 65:
print("ํ• ์ธ ๋Œ€์ƒ")

# not operator
is_weekend = False
if not is_weekend:
print("ํ‰์ผ์ž…๋‹ˆ๋‹ค")

# Complex conditions
score = 85
attendance = 0.9

if (score >= 80 and attendance >= 0.8) or score >= 95:
print("ํ•ฉ๊ฒฉ")

Loops (for loop)โ€‹

Basic for loopโ€‹

# Iterate over list
fruits = ["์‚ฌ๊ณผ", "๋ฐ”๋‚˜๋‚˜", "์ฒด๋ฆฌ"]
for fruit in fruits:
print(fruit)

# Iterate over string
for char in "Python":
print(char)

# Using 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

Index and value with enumerateโ€‹

fruits = ["์‚ฌ๊ณผ", "๋ฐ”๋‚˜๋‚˜", "์ฒด๋ฆฌ"]

for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: ์‚ฌ๊ณผ
# 1: ๋ฐ”๋‚˜๋‚˜
# 2: ์ฒด๋ฆฌ

# Specify starting index
for index, fruit in enumerate(fruits, 1):
print(f"{index}. {fruit}")
# 1. ์‚ฌ๊ณผ
# 2. ๋ฐ”๋‚˜๋‚˜
# 3. ์ฒด๋ฆฌ

Iterate multiple sequences simultaneously with zipโ€‹

names = ["ํ™๊ธธ๋™", "๊น€์ฒ ์ˆ˜", "์ด์˜ํฌ"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
print(f"{name}: {score}์ ")
# ํ™๊ธธ๋™: 85์ 
# ๊น€์ฒ ์ˆ˜: 92์ 
# ์ด์˜ํฌ: 78์ 

# Different lengths (stops at the shortest)
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

Iterate over dictionaryโ€‹

person = {"name": "ํ™๊ธธ๋™", "age": 25, "city": "์„œ์šธ"}

# Iterate over keys
for key in person:
print(key)

# Iterate over values
for value in person.values():
print(value)

# Iterate over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")

Nested loopsโ€‹

# Multiplication table
for i in range(2, 10):
for j in range(1, 10):
print(f"{i} x {j} = {i*j}")
print() # ๋‹จ ์‚ฌ์ด ๋นˆ ์ค„

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

for row in matrix:
for value in row:
print(value, end=" ")
print() # ์ค„๋ฐ”๊ฟˆ

Loops (while loop)โ€‹

Basic while loopโ€‹

# Countdown
count = 5
while count > 0:
print(count)
count -= 1
print("๋ฐœ์‚ฌ!")

# Until condition is met
number = 1
while number < 100:
number *= 2
print(number) # 128

Infinite loopโ€‹

# Repeat user input
while True:
answer = input("๊ณ„์†ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (y/n): ")
if answer.lower() == 'n':
break
print("๊ณ„์†ํ•ฉ๋‹ˆ๋‹ค...")

print("์ข…๋ฃŒ")

while-elseโ€‹

# else executes when condition becomes False (normal termination)
count = 0
while count < 3:
print(count)
count += 1
else:
print("์ •์ƒ ์ข…๋ฃŒ")

# else doesn't execute when terminated with break
count = 0
while count < 10:
if count == 3:
break
count += 1
else:
print("์ด ๋ถ€๋ถ„์€ ์‹คํ–‰ ์•ˆ ๋จ")

Loop Controlโ€‹

break - Exit loopโ€‹

# Exit when desired value is found
numbers = [1, 3, 5, 7, 9, 2, 4, 6]

for num in numbers:
if num % 2 == 0:
print(f"์ฒซ ๋ฒˆ์งธ ์ง์ˆ˜: {num}")
break

# break in nested loops
found = False
for i in range(10):
for j in range(10):
if i * j > 50:
found = True
break
if found:
break

continue - Skip to next iterationโ€‹

# Print only odd numbers
for i in range(1, 11):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9

# Skip specific values
words = ["apple", "banana", "", "cherry", ""]
for word in words:
if not word:
continue
print(word.upper())

pass - Do nothingโ€‹

# Code to be implemented later
for i in range(5):
if i == 2:
pass # TODO: ๋‚˜์ค‘์— ๊ตฌํ˜„
else:
print(i)

# Empty class or function
class MyClass:
pass # ์ผ๋‹จ ๋ผˆ๋Œ€๋งŒ

def my_function():
pass # ๋‚˜์ค‘์— ๊ตฌํ˜„

Practical Examplesโ€‹

Prime number checkโ€‹

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=" ")

Greatest Common Divisor (GCD)โ€‹

def gcd(a, b):
"""์œ ํด๋ฆฌ๋“œ ํ˜ธ์ œ๋ฒ•"""
while b != 0:
a, b = b, a % b
return a

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

Fibonacci sequenceโ€‹

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=" ")

Number guessing gameโ€‹

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()
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)

Simple calculatorโ€‹

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() # ์ฃผ์„ ํ•ด์ œํ•˜์—ฌ ์‹คํ–‰

Star patternsโ€‹

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()

Grade processingโ€‹

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() # ์ฃผ์„ ํ•ด์ œํ•˜์—ฌ ์‹คํ–‰

Frequently Asked Questionsโ€‹

Q1. Should I use for or while?โ€‹

A: Choose based on the situation

# for: When you know the number of iterations
for i in range(10):
print(i)

# while: Until a condition is met
while user_input != "quit":
user_input = input("๋ช…๋ น: ")

# Practical choice
# - Iterate collections: for
# - Condition-based iteration: while
# - Infinite loop: while True

Q2. range vs enumerate, which to use?โ€‹

A: Use enumerate if you need both index and value

fruits = ["์‚ฌ๊ณผ", "๋ฐ”๋‚˜๋‚˜", "์ฒด๋ฆฌ"]

# โŒ Not recommended
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")

# โœ… Recommended
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")

Q3. What's the difference between break and return?โ€‹

A: break only exits the loop, return exits the function

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. How do I prevent infinite loops?โ€‹

A: Make conditions and exit conditions clear

# โŒ Dangerous infinite loop
count = 0
while count < 10:
print(count)
# count๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค์ง€ ์•Š์Œ!

# โœ… Safe loop
count = 0
max_iterations = 1000 # ์•ˆ์ „์žฅ์น˜
while count < 10 and max_iterations > 0:
print(count)
count += 1
max_iterations -= 1

# โœ… Clear exit condition
while True:
user_input = input("์ž…๋ ฅ (q=์ข…๋ฃŒ): ")
if user_input == 'q':
break
process(user_input)

Next Stepsโ€‹

You've mastered program flow control!

Key takeaways:
โœ… Conditional branching with if-elif-else
โœ… Iterate collections with for
โœ… Condition-based iteration with while
โœ… Control with break, continue, pass
โœ… Practical examples (games, calculator, etc.)

Next step: Learn to make code reusable in Functions!