Control Flow
If statements, loops, and controlling program flow with conditions.
If Statements
- Execute code based on conditions.
- Use if, elif (else if), and else.
- Indentation defines the code block.
age = 18
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")
# Nested if
score = 85
if score >= 60:
if score >= 90:
print("A grade")
else:
print("B grade")
For Loops
- Iterate over sequences (lists, strings, ranges).
- Use range() for numeric loops.
- Access index with enumerate().
# Loop through range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Loop through list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# With index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
While Loops
- Repeat while condition is True.
- Be careful to avoid infinite loops.
- Use break to exit loop early.
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# With break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
Loop Control
- break: Exit loop immediately
- continue: Skip to next iteration
- pass: Do nothing (placeholder)
# break example
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue example
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4
# pass example
for i in range(3):
pass # TODO: implement later