Loops and Conditionals: How Programs Make Decisions
So far, programs execute one line after another—straight through. But real programs need to make decisions ("if this, do that") and repeat actions ("do this 100 times"). That's where conditionals and loops come in.
These control structures are essential to programming. They transform simple scripts into powerful, flexible programs.
Conditionals: Making Decisions
Conditionals let programs choose different paths based on conditions.
The Basic If Statement:
\\\`python
temperature = 75
if temperature > 80:
print("It's hot!")
\\\`
If the condition (temperature > 80) is True, the indented code runs. If False, it's skipped.
If-Else: Two Paths:
\\\`python
temperature = 75
if temperature > 80:
print("It's hot!")
else:
print("It's not too hot.")
\\\`
Now there's always a response—one path or the other.
If-Elif-Else: Multiple Paths:
\\\`python
temperature = 75
if temperature > 90:
print("It's very hot!")
elif temperature > 80:
print("It's hot!")
elif temperature > 60:
print("It's pleasant.")
else:
print("It's cool.")
\\\`
Python checks each condition in order. The first True condition triggers; the rest are skipped.
Comparison Operators
Conditions use comparison operators:
| Operator | Meaning | Example |
|----------|---------|---------|
| == | Equal to | x == 5 |
| != | Not equal to | x != 5 |
| > | Greater than | x > 5 |
| < | Less than | x < 5 |
| >= | Greater or equal | x >= 5 |
| <= | Less or equal | x <= 5 |
Logical Operators
Combine conditions with logical operators:
and: Both must be True
\\\`python
if age >= 18 and has_license:
print("You can drive!")
\\\`
or: At least one must be True
\\\`python
if is_weekend or is_holiday:
print("No work today!")
\\\`
not: Reverses True/False
\\\`python
if not is_logged_in:
print("Please log in.")
\\\`
Loops: Repeating Actions
Loops repeat code—essential for processing lists, retrying operations, or running until a condition is met.
For Loops: Known Iterations
When you know how many times to repeat:
\\\`python
Print numbers 1 to 5
for i in range(1, 6):
print(i)
Process each item in a list
names = ["Alice", "Bob", "Charlie"] for name in names: print(f"Hello, {name}!") \\\`
For loops iterate through a sequence—each item gets processed once.
While Loops: Unknown Iterations
When you don't know how many times, but know when to stop:
\\\`python
count = 0
while count < 5:
print(count)
count = count + 1
\\\`
The loop continues as long as the condition is True.
Careful! While loops can run forever if the condition never becomes False:
\\\`python
DANGER: Infinite loop!
while True:
print("This never stops!")
\
\\`
Loop Control: Break and Continue
break: Exit the loop immediately
\\\`python
for number in range(100):
if number == 5:
break # Stop at 5
print(number)
Prints: 0, 1, 2, 3, 4
\
\\`
continue: Skip to the next iteration
\\\`python
for number in range(5):
if number == 2:
continue # Skip 2
print(number)
Prints: 0, 1, 3, 4
\
\\`
Nested Structures
Conditionals and loops can be nested inside each other:
\\\`python
for x in range(1, 4):
for y in range(1, 4):
print(f"{x} x {y} = {x * y}")
\\\`
This creates a multiplication table—the inner loop runs completely for each iteration of the outer loop.
Practical Examples
Finding an item:
\\\`python
numbers = [4, 2, 8, 5, 1, 9]
target = 5
for number in numbers:
if number == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found.")
\\\`
Input validation:
\\\`python
while True:
password = input("Enter password: ")
if len(password) >= 8:
print("Password accepted!")
break
else:
print("Password must be 8+ characters. Try again.")
\\\`
Filtering a list:
\\\`python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for number in numbers:
if number % 2 == 0: # Check if even
evens.append(number)
print(evens) # [2, 4, 6, 8, 10]
\\\`
Common Patterns
Accumulator Pattern: Build up a result
\\\`python
total = 0
for number in [1, 2, 3, 4, 5]:
total = total + number
print(total) # 15
\\\`
Counter Pattern: Count occurrences
\\\`python
count = 0
for char in "hello world":
if char == "l":
count = count + 1
print(count) # 3
\\\`
Search Pattern: Find something
\\\`python
found = False
for item in items:
if item == target:
found = True
break
\\\`
Connecting to Algorithms
Remember algorithms? Loops and conditionals are how algorithms become code. The "find largest number" algorithm translates directly:
\\\`python
numbers = [5, 2, 9, 1, 7]
largest = numbers[0] # Start with first
for number in numbers:
if number > largest:
largest = number
print(largest) # 9
\\\`
Every algorithm you'll encounter uses these structures.
Related Reading
Listen to the Full Course
Master programming logic in Learn to Code: Programming Fundamentals.