Logic and Control Flow
Teaching the computer how to make decisions and repeat actions intelligently.
Comparison Operators: The Language of Logic
Computers make decisions by comparing values. These operators let your code ask questions and get true or false answers.
== Equal To != Not Equal > Greater Than
Checks if two values are the same Checks if values are different Tests if left side is larger
5 == 5 # True 10 != 5 # True 15 > 10 # True
"hi" == "hello" # False "cat" != "cat" # False 3 > 8 # False
< Less Than >= Greater or Equal <= Less or Equal
Tests if left side is smaller True if larger or same True if smaller or same
5 < 10 # True 10 >= 10 # True 7 <= 9 # True
If-Else Statements: Making Decisions
If-else statements let your program choose different actions based on conditions. Think of them as
decision trees that guide your code's behavior.
Basic If Statement If-Else Statement
age = 18 temperature = 65
if age >= 18: if temperature > 70:
print("You can vote!") print("It's warm outside")
print("Congratulations!") else:
print("Bring a jacket")
Code inside the if block only runs when the
condition is True. The else block provides an alternative action
when the condition is False.
Pro Tip: Indentation matters! Python uses indentation to group code blocks. Everything
indented under an if statement belongs to that decision branch.
Nested Decisions: Elif
Real decisions often have more than two choices. The elif (else-if) statement lets you check multiple conditions in sequence.
Check First Condition
score = 85
if score >= 90:
If true, execute this block and skip the rest
Check Second Condition
elif score >= 80:
Only checked if previous condition was false
Check Third Condition
elif score >= 70:
Continues checking down the chain
Final Fallback
else:
Runs if no conditions above were true
While Loops: Repeating with Purpose
A while loop repeats a block of code as long as a condition remains true. It's perfect when you don't know exactly how many times you need to repeat something.
How While Loops Work
count = 1
while count <= 5:
print(f"Count is: {count}")
count = count + 1
print("Done!")
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Done!
Check Condition
Is it still true?
Execute Code
Run the block
Update Variable
For Loops: Iterating Over Sequences
For loops are perfect when you know exactly what you want to iterate over—like items in a list or a range of numbers. They
automatically handle the counting for you.
Looping Through Lists
fruits = ["apple", "banana", "cherry"]
1
for fruit in fruits:
print(f"I like {fruit}")
The loop automatically assigns each item to the variable "fruit" one at a time.
Using Range for Numbers
for i in range(1, 6):
2
print(f"Number: {i}")
range(1, 6) generates numbers from 1 to 5. The end number is not included.
Range with Steps
for i in range(0, 10, 2):
3
print(i)
The third argument is the step size. This prints: 0, 2, 4, 6, 8
While vs For: Choosing the Right
Loop
Use While Loops When... Use For Loops When...
• You don't know how many iterations • You know the exact number of
you need iterations
• The loop depends on user input or • You're processing items in a collection
changing conditions
• You're waiting for something to happen • You need a counter variable
numbers = [10, 20, 30, 40]
password = ""
for num in numbers:
while password != "secret": print(num * 2)
password = input("Enter password:
")
print("Access granted!")
Breaking Out: The Break Statement
Sometimes you need to exit a loop early when a specific condition is met. The break statement immediately stops the loop and continues with the code after it.
01 02
Loop Starts Normally Break Condition Met
Iteration begins as usual Special condition triggers break
03 04
Exit Immediately Continue After Loop
Loop stops, skips remaining iterations Code execution resumes below loop
Break in While Loop Break in For Loop
count = 1 for number in range(1, 11):
if number == 6:
while count <= 10: break
print(count) print(number)
if count == 5:
break print("Found 6, stopped!")
count += 1
print("Loop ended early!")
Continuing Forward: The Continue Statement
Unlike break, the continue statement doesn't exit the loop entirely. Instead, it skips the rest of the current iteration and jumps to the next one.
Without Continue With Continue
for i in range(1, 6): for i in range(1, 6):
print(f"Processing {i}") if i == 3:
print("Task complete") continue
print("---") print(f"Processing {i}")
print("Task complete")
Output: Everything prints for each number print("---")
Output: Skips printing when i equals 3
Use Case: Skip Even Numbers Use Case: Filter Invalid Data
for num in range(1, 11): scores = [85, -1, 92, 0, 78]
if num % 2 == 0:
continue for score in scores:
print(num) if score < 0:
continue
This prints only odd numbers: 1, 3, 5, 7, 9 print(f"Valid score: {score}")
Skips processing negative scores
Mastering Control Flow: Key Takeaways
Comparison Operators
Use ==, !=, >, <, >=, <= to compare values and make logical decisions in your code.
If-Else Statements
Create decision trees with if, elif, and else to execute different code based on conditions.
While & For Loops
Use while for unknown iterations, for when you know the sequence. Both let you repeat code efficiently.
Break & Continue
Break exits loops early; continue skips to the next iteration. Both give you fine control over loop execution.
Practice Tip: The best way to master control flow is to experiment! Try combining loops with conditionals, nest if statements, and use
break/continue in different scenarios.