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()
Print calendarโ
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!