Program Flow: Controlling What Your Code Does
Core Idea: Program flow (or control flow) lets your program make decisions and repeat actions based on conditions.
1. If Statements: Doing Something Based on a Condition
Purpose: Executes a block of code only if a specified condition is true. Optionally includes else to execute a different block if the condition is false.
Basic Structure:
Python:
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false
C:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Key Differences (Python vs. C):
- Code Blocks:
- Python: Uses indentation to define code blocks (lines with the same indentation level belong to the same block).
- C: Uses curly braces
{} to define code blocks. Braces can be omitted for single-line blocks.
- elif (Python) / else if (C): Used to check multiple conditions in sequence. The
elif/else if condition is only evaluated if the preceding if or elif/else if condition was false.
Python:
if condition1:
# Code for condition1
elif condition2:
# Code for condition2
else:
# Code if neither condition1 nor condition2 is true
C:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if neither condition1 nor condition2 is true
}
2. Looping: Repeating Actions
Purpose: Executes a block of code repeatedly.
Types:
- while loop: Repeats as long as a condition is true.
Python:
while condition:
# Code to repeat
C:
while (condition) {
// Code to repeat
}
Important: Make sure the condition eventually becomes false to avoid an infinite loop!
- for loop: Iterates over a sequence of values (numbers, items in a list, etc.).
C Style (for with numeric range):
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}
- initialization: Executed once at the beginning of the loop (e.g.,
int x = 1;).
- condition: Checked before each iteration. The loop continues as long as the condition is true (e.g.,
x <= 10;).
- increment/decrement: Executed after each iteration (e.g.,
x++;).
Python Style (for with collection):
for item in collection:
# Code to execute for each item in the collection
- collection: A list, tuple, string, or other iterable object.
- item: A variable that takes on the value of each item in the collection during each loop iteration.