Control Flow: if, for, and while
Control Flow: if, for, and while
Making Decisions with if
Programs are more than straight lines of instructions. Control flow lets your code make decisions and repeat work. The if statement runs a block only when a condition is True, and optional elif and else branches handle other cases.
score = 78
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
print(grade) # B
Notice the colon after the condition and the indented body. Conditions can be combined with and, or, and not. Parentheses keep complex conditions readable.
Repeating with for
The for loop iterates over any iterable, most commonly a range of numbers or a list. range(5) produces 0, 1, 2, 3, 4, while range(2, 10, 2) steps from 2 to 9 in steps of 2.
total = 0
for number in range(1, 6):
total += number
print(total) # 15
You can also loop directly over a string to visit each character, or over a dictionary to visit its keys.
Repeating with while
The while loop keeps running as long as its condition stays True. Use it when you do not know in advance how many iterations you need. A counter inside the body moves the loop toward its end, and break exits early while continue skips to the next iteration.
guess = 0
answer = 42
while guess != answer:
guess = int(input("Enter a number: "))
print("Correct!")
Choosing the Right Tool
As a rule of thumb, use for when you know what you are iterating over and while when the loop depends on a condition that changes during execution. Both loops can nest, meaning you can place one loop inside another to handle rows and columns or pairs of items.
Key Points
- if, elif, and else choose between branches based on boolean conditions.
- Combine conditions with and, or, and not.
- for iterates over ranges, lists, strings, and dictionaries.
- while repeats until a condition becomes False; break and continue fine-tune it.
- Use for for known iterations and while for condition-driven loops.