Control Flow: Beginner

Uber's surge pricing algorithm uses chains of if and elif conditions to compute price multipliers by evaluating supply levels, rider demand, local weather, and nearby events all at once, making these decisions in milliseconds for millions of simultaneous ride requests across hundreds of cities. A single trip request might trigger dozens of conditional checks before a multiplier is assigned, and each branch of that logic directly affects how much a rider pays and how quickly a driver responds. The same fundamental conditional structure you are about to learn is what allows Uber to encode complex business rules into code that runs reliably under enormous real-time pressure. By the end of this lesson, you will understand exactly how to build the kind of branching decision logic that powers systems like Uber's pricing engine.

The if Statement

Daily Life
Interviews

Run code only when conditions are true

The if statement is the most fundamental control flow construct. It evaluates a condition, and if that condition is true, it executes the indented code block that follows. If the condition is false, the code block is skipped entirely.

The word "if" means exactly what it does in English: "if this is true, do that." Python checks the condition, and only runs the indented code when the condition evaluates to True.

Basic if Syntax

An if statement consists of the keyword if, followed by a condition, followed by a colon :. The code to execute when true must be indented (typically 4 spaces):

1age = 21
2
3if age >= 18:
4 print("You are an adult")
5 print("You can vote")
6
7print("This always runs")
>>>Output
You are an adult
You can vote
This always runs
Both indented print statements run because age is 21, which is greater than or equal to 18. The final print statement runs regardless of the condition because it is not indented under the if.

When Conditions Are False

When the condition evaluates to False, Python skips the entire indented block and continues with the next unindented line:
1temperature = 15
2
3if temperature > 30:
4 print("It's hot outside")
5 print("Turn on the AC")
6
7print("Weather check complete")
>>>Output
Weather check complete
Since 15 is not greater than 30, the condition is False and both indented lines are skipped. Only the final unindented line executes.

Conditions and Booleans

The condition in an if statement must evaluate to a boolean value (True or False). Comparison operators naturally produce boolean results:

1x = 10
2y = 5
3
4# Comparison operators produce True or False
5print("x > y:", x > y)
6print("x < y:", x < y)
7print("x == y:", x == y)
8print("x != y:", x != y)
9print("x >= 10:", x >= 10)
10print("x <= 10:", x <= 10)
>>>Output
x > y: True
x < y: False
x == y: False
x != y: True
x >= 10: True
x <= 10: True

Notice that equality comparison uses == (two equals signs), not = (single equals, which is assignment). This is a common source of errors.

Each comparison operator serves a different purpose. Here is a quick reference for the six operators you will use most often in conditional logic:
== Equal to
True when both sides have the same value
!= Not equal
True when the two sides differ in value
> and < Ordering
Checks if left is strictly greater or less than right
>= and <= Inclusive
Includes the boundary value in the comparison

Collection Conditions

Conditions work with any data type, not just numbers. You can compare strings, check membership in collections, and more:
1status = "active"
2allowed_statuses = ["active", "pending", "approved"]
3
4if status == "active":
5 print("User account is active")
6
7if status in allowed_statuses:
8 print("Status is valid")
9
10name = "Alice"
11if len(name) > 0:
12 print("Name is not empty")
>>>Output
User account is active
Status is valid
Name is not empty
TIP
The in operator checks membership. It returns True if the left value exists in the right collection. This works with lists, strings, sets, and dictionary keys.

Truthy and Falsy Values

Python evaluates any value as True or False in a conditional context. Empty collections, zero, None, and empty strings are "falsy" (treated as False). Everything else is "truthy" (treated as True). This allows concise conditions:

1# Falsy values
2items = []
3if items:
4 print("List has items")
5else:
6 print("List is empty")
7
8# Truthy values
9name = "Alice"
10if name:
11 print("Name is set:", name)
12
13data = None
14if data:
15 print("Processing data")
16else:
17 print("No data to process")
>>>Output
List is empty
Name is set: Alice
No data to process
NoneFalse0""[]{}
None
Null value
Represents nothing at all
False
Boolean False
The explicit false value
0
Zero
Integer or float zero
""
Empty string
A string with no content
[]
Empty list
A list with zero elements
{}
Empty dict
A dict with no entries
Fill in the Blank

> You have an empty list and need to check whether it contains items. Pick the right condition.

items = []
if :
    print("empty")
else:
    print("has items")

Python's truthy and falsy rules make conditions concise. Checking if items: is shorter and clearer than if len(items) > 0:, and it handles None gracefully as well since None is also falsy.

The in operator is one of the most readable ways to check membership. Using status in valid_statuses communicates intent clearly compared to a long chain of equality comparisons.

Comparison operators always return a boolean result. You can store that result in a variable to reuse the check multiple times without re-evaluating the condition.

Branching with if-else

Daily Life
Interviews

Choose between two code paths

Often you need to choose between two alternatives: do one thing if a condition is true, or do something else if it's false. The else clause provides this "otherwise" path. The else block executes only when the if condition is False.

Basic if-else Structure

The else keyword comes after the if block, at the same indentation level as if, followed by a colon:

1balance = 150
2
3if balance >= 100:
4 print("Sufficient funds")
5 print("Transaction approved")
6else:
7 print("Insufficient funds")
8 print("Transaction declined")
9
10print("Processing complete")
>>>Output
Sufficient funds
Transaction approved
Processing complete
Since balance is 150, the condition is True, so the if block runs and the else block is skipped. Exactly one of the two blocks will always execute.

The else Block Executes

When the condition is False, the else block runs instead:
1balance = 50
2
3if balance >= 100:
4 print("Sufficient funds")
5 print("Transaction approved")
6else:
7 print("Insufficient funds")
8 print("Transaction declined")
9
10print("Processing complete")
>>>Output
Insufficient funds
Transaction declined
Processing complete
Now balance is 50, so the condition is False. Python skips the if block entirely and executes the else block. The final print still runs because it is outside both blocks.

Mutually Exclusive Paths

With if-else, exactly one of the two code blocks will always run. They are mutually exclusive: if one runs, the other does not. This is useful when you have exactly two possibilities:
1number = 7
2
3if number % 2 == 0:
4 parity = "even"
5else:
6 parity = "odd"
7
8print(str(number) + " is " + parity)
9
10# Another example: absolute value
11value = -15
12
13if value >= 0:
14 absolute = value
15else:
16 absolute = -value
17
18print("Absolute value:", absolute)
>>>Output
7 is odd
Absolute value: 15

The modulo operator % returns the remainder after division. If a number divided by 2 has remainder 0, it is even; otherwise it is odd.

Data Validation Example

In data engineering, if-else is commonly used for validation and categorization:
1# Validate a user age value
2user_age = 25
3
4if user_age >= 0 and user_age <= 120:
5 print("Valid age:", user_age)
6 status = "valid"
7else:
8 print("Invalid age:", user_age)
9 status = "invalid"
10
11print("Validation status:", status)
12
13# Categorize transaction amount
14amount = 5000
15
16if amount >= 10000:
17 category = "large"
18else:
19 category = "standard"
20
21print("Transaction category:", category)
>>>Output
Valid age: 25
Validation status: valid
Transaction category: standard
Debug Challenge

> This code checks if a number is even, but uses the wrong operator in the condition. Fix the syntax error.

SyntaxError: invalid syntax. Cannot use assignment operator = in a condition.

The single equals sign is reserved for assignment. Python raises a SyntaxError immediately when it sees "=" inside a condition, so this mistake is caught before your code ever runs.
The if-else structure guarantees exactly one branch will execute. This makes it the right tool when you need to cover every possible case with no gaps and no overlap between the two paths.
In data validation pipelines, if-else is often used to route records into two streams: rows that pass validation continue through the pipeline, while rows that fail are written to a quarantine table for review.

Chaining if-elif-else

Daily Life
Interviews

Route logic through multiple branches

When you have more than two possibilities, use elif (short for "else if"). An elif clause lets you check additional conditions when the previous conditions were False. You can chain as many elif clauses as needed.

Basic elif Syntax

Each elif has its own condition. Python checks conditions from top to bottom and executes the first block whose condition is True:

1score = 85
2
3if score >= 90:
4 grade = "A"
5elif score >= 80:
6 grade = "B"
7elif score >= 70:
8 grade = "C"
9elif score >= 60:
10 grade = "D"
11else:
12 grade = "F"
13
14print("Score:", score)
15print("Grade:", grade)
>>>Output
Score: 85
Grade: B
With a score of 85, the first condition (score >= 90) is False. Python moves to the first elif (score >= 80), which is True, so grade becomes "B". All remaining elif and else blocks are skipped.

Order Matters

Python evaluates conditions from top to bottom and stops at the first True condition. The order of your conditions is crucial:
1# CORRECT order: specific to general
2age = 25
3
4if age < 13:
5 category = "child"
6elif age < 20:
7 category = "teenager"
8elif age < 65:
9 category = "adult"
10else:
11 category = "senior"
12
13print("Age", age, "is category:", category)
>>>Output
Age 25 is category: adult
If you reversed the order and checked age < 65 first, everyone under 65 would be classified as "adult" regardless of whether they are children or teenagers. Always order conditions from most specific to most general.

Multiple elif Clauses

You can have as many elif clauses as needed. This is useful for categorizing data into multiple buckets. In data engineering, this pattern appears when you need to classify records into different categories, map status codes to human-readable messages, or apply different processing logic based on data types:
1http_status = 404
2
3if http_status == 200:
4 message = "OK - Success"
5elif http_status == 201:
6 message = "Created"
7elif http_status == 400:
8 message = "Bad Request"
9elif http_status == 401:
10 message = "Unauthorized"
11elif http_status == 403:
12 message = "Forbidden"
13elif http_status == 404:
14 message = "Not Found"
15elif http_status == 500:
16 message = "Internal Server Error"
17else:
18 message = "Unknown Status"
19
20print("Status", http_status, ":", message)
>>>Output
Status 404 : Not Found

elif vs Multiple if

There is an important difference between using elif and using multiple separate if statements:
if-elif-else
  • Exactly ONE block executes
  • Stops at first true condition
  • Mutually exclusive branches
  • More efficient
Multiple if
  • MULTIPLE blocks can execute
  • Checks ALL conditions
  • Independent conditions
  • Use when conditions overlap
1value = 15
2
3if value > 10:
4 print("Greater than 10")
5if value > 5:
6 print("Greater than 5")
7
8print("---")
9
10if value > 10:
11 print("Greater than 10")
12elif value > 5:
13 print("Greater than 5")
>>>Output
Greater than 10
Greater than 5
---
Greater than 10
With separate if statements, both conditions are checked and both blocks run. With if-elif, Python stops after the first true condition.
Fill in the Blank

> A grading system needs to handle multiple score ranges. Pick the correct keyword for the middle condition.

score = 75
if score >= 90:
    grade = "A"
 score >= 80:
    grade = "B"
else:
    grade = "C"
print(grade)

The elif keyword is Python's way of linking conditions into a single chain. Unlike separate if statements, only one branch in an if-elif-else chain will ever run, which prevents duplicate logic from accidentally executing.

Order matters in elif chains. Python stops at the first true condition, so placing broader conditions before narrower ones can cause logic errors. Always arrange conditions from most specific to most general.

When you have more than five or six elif branches, consider replacing the chain with a dictionary lookup. Dictionaries are O(1) and easier to extend than long chains where conditions must be checked in sequence.

Combining with and/or

Daily Life
Interviews

Combine conditions with boolean logic

Often a single comparison is not enough. You need to check multiple conditions together. Python provides logical operators to combine conditions: and requires all conditions to be true, or requires at least one condition to be true, and not inverts a condition.

The and Operator

The and operator returns True only if BOTH conditions are True. If either condition is False, the entire expression is False. This is essential for validation where multiple requirements must all be met. For example, a user might need to be both logged in AND have permission to access a resource. A transaction might need to be both under the limit AND from a verified account:

1age = 25
2has_license = True
3
4# Both must be true
5if age >= 18 and has_license:
6 print("Can drive")
7else:
8 print("Cannot drive")
9
10# Test with different values
11temperature = 72
12humidity = 45
13
14if temperature >= 65 and temperature <= 80 and humidity < 60:
15 print("Perfect weather!")
16else:
17 print("Weather could be better")
>>>Output
Can drive
Perfect weather!

All conditions connected by and must be True for the block to execute. You can chain multiple and operators together.

The or Operator

The or operator returns True if AT LEAST ONE condition is True. It only returns False if all conditions are False:

1day = "Saturday"
2
3if day == "Saturday" or day == "Sunday":
4 print("It's the weekend!")
5else:
6 print("It's a weekday")
7
8is_admin = False
9is_moderator = True
10is_owner = False
11
12if is_admin or is_moderator or is_owner:
13 print("User has elevated privileges")
14else:
15 print("Standard user")
>>>Output
It's the weekend!
User has elevated privileges

Only one condition needs to be True for the entire expression to be True. The user is a moderator, so they have elevated privileges even though they are not an admin or owner.

The not Operator

The not operator inverts a boolean value. True becomes False, and False becomes True:

1is_blocked = False
2
3if not is_blocked:
4 print("User can access the system")
5
6# Equivalent to checking is_blocked == False
7# but "not is_blocked" reads more naturally
8
9items = []
10
11if not items:
12 print("List is empty")
13
14# Check if value is NOT in a collection
15status = "cancelled"
16valid_statuses = ["pending", "active", "completed"]
17
18if status not in valid_statuses:
19 print("Invalid status:", status)
>>>Output
User can access the system
List is empty
Invalid status: cancelled
TIP
Empty collections (empty lists, empty strings, empty dicts) are "falsy" in Python. if not items: is a Pythonic way to check if a collection is empty.

Combining and, or, not

You can combine logical operators to build complex conditions. Use parentheses to make the logic clear and control evaluation order:
1age = 25
2is_student = True
3income = 30000
4
5if (age < 30 and is_student) or income < 25000:
6 print("Eligible for discount")
7else:
8 print("Standard pricing")
9
10# Validation with multiple checks
11email = "user@example.com"
12password = "secure123"
13
14if email and password and "@" in email:
15 print("Login attempt valid")
16else:
17 print("Invalid login data")
>>>Output
Eligible for discount
Login attempt valid

Operator precedence: not is evaluated first, then and, then or. When in doubt, use parentheses to make your intent explicit.

Debug Challenge

> This weekend check always returns True because of how Python evaluates the or expression. Fix the logic error.

Logic error: this condition is always True because "Sunday" is a truthy string.

Every operand of or must be a complete boolean expression. Writing day == "Saturday" or "Sunday" is a common mistake because Python reads "Sunday" as a standalone truthy value rather than as a second comparison target.

Short-circuit evaluation means Python stops evaluating or as soon as it finds a truthy value. For and, it stops at the first falsy value. Understanding this behavior helps you order conditions for both correctness and efficiency.

Parentheses can make compound conditions much easier to read. Wrapping related conditions in parentheses makes the grouping explicit and prevents subtle bugs from operator precedence surprises.
Python Quiz

> Choose the boolean operators that make this weather planner work correctly. The beach requires BOTH warmth and sun; the park needs at least one.

temp = 72
sunny = False
if temp > 70 ___ sunny:
    plan = "beach"
elif temp > 70 ___ sunny:
    plan = "park"
else:
    plan = "home"
print(plan)
or
is
in
and
not

The and and or operators let you express requirements precisely. and is for situations where all conditions must be satisfied simultaneously; or is for situations where meeting any one of several criteria is sufficient.

Logical operators are evaluated in a fixed order of precedence: not first, then and, then or. Using parentheses to override this order makes your intent clear and prevents hard-to-spot logic bugs.

Compound conditions are the building blocks of data filtering. Almost every query, validation rule, and business logic check you write will combine simple comparisons using and, or, and not.

Execution Flow

Daily Life
Interviews

Trace how Python picks which lines run

Understanding how Python decides which lines to execute is fundamental to writing correct programs. In Python, indentation is not just for readability; it determines which code belongs together and when it runs.

Indentation and Execution

When you indent code under an if statement, you are telling Python: "only run these lines if the condition is True." The indentation level defines a block of code that executes together:
1is_raining = True
2
3if is_raining:
4 print("Grab an umbrella")
5 print("Wear rain boots")
6print("Head out the door")
>>>Output
Grab an umbrella
Wear rain boots
Head out the door
The two indented print statements form a single block. They either both run (when is_raining is True) or both get skipped (when False). The unindented line runs regardless of the condition.
1is_raining = False
2
3if is_raining:
4 print("Grab an umbrella")
5 print("Wear rain boots")
6print("Head out the door")
>>>Output
Head out the door
TIP
Think of indentation as creating "rooms" of code. Everything at the same indent level is in the same room and shares the same fate: they all run together or all get skipped together.
When Python encounters an if-elif-else chain, it follows a predictable sequence of steps to determine which block to execute:
01
Read condition
Python evaluates the boolean expression after if or elif
02
Check truthiness
The result is tested: is it True or False?
03
Branch or skip
If True, enter the indented block. If False, jump to the next elif or else
04
Resume after
After one block executes, skip all remaining elif/else and continue below

Nested Blocks

You can place if statements inside other if statements, creating nested blocks. Each level of indentation creates a new execution context that depends on all outer conditions being True:
1has_account = True
2is_verified = True
3
4if has_account:
5 print("Account found")
6 if is_verified:
7 print("Account verified")
8 print("Access granted")
9 else:
10 print("Please verify account")
11else:
12 print("No account found")
>>>Output
Account found
Account verified
Access granted
The innermost print statements only run when both has_account AND is_verified are True. If has_account were False, none of the inner checks would even be evaluated.

Nesting vs Combining

Nested conditionals can often be rewritten using and. Choose based on whether you need different else blocks at each level:

1age = 25
2has_id = True
3
4if age >= 18:
5 if has_id:
6 print("Entry allowed")
7
8if age >= 18 and has_id:
9 print("Entry allowed")
>>>Output
Entry allowed
Entry allowed
TIP
Avoid nesting more than 2-3 levels deep. If your code forms an arrow pointing right, consider combining conditions or extracting logic into functions.

Data Validation Patterns

One of the most common uses of control flow in data engineering is validating input data. Here is a comprehensive example that checks multiple aspects of a data record:
1customer = {"name": "Alice", "email": "a@b.com", "age": 28}
2
3errors = []
4if not customer.get("name"):
5 errors.append("Name required")
6if "@" not in customer.get("email", ""):
7 errors.append("Invalid email")
8if not 0 <= customer.get("age", -1) <= 150:
9 errors.append("Invalid age")
10
11if errors:
12 print("Errors:", errors)
13else:
14 print("Valid:", customer["name"])
>>>Output
Valid: Alice
This pattern of accumulating validation errors is very common. Each check is independent, so we use separate if statements rather than if-elif. This allows us to catch all problems at once rather than stopping at the first error.

Short-Circuit Evaluation

Python uses short-circuit evaluation for and and or operators. This means Python stops evaluating as soon as it knows the final result. With and, if the first condition is False, Python does not evaluate the second. With or, if the first condition is True, Python does not evaluate the second. This is both an optimization and a safety feature:

1# Short-circuit prevents errors
2data = None
3
4# This would crash without short-circuit:
5# len(data) > 0 # TypeError if None
6
7# Safe version using short-circuit
8if data and len(data) > 0:
9 print("Data has", len(data), "items")
10else:
11 print("No data available")
12
13# Another example: safe dictionary access
14user = {"name": "Alice"}
15
16# Check key exists before using value
17if "email" in user and "@" in user["email"]:
18 print("Valid email")
19else:
20 print("No valid email")
21
22# Short-circuit with 'or' for defaults
23name = None
24display_name = name or "Guest"
25print("Hello,", display_name)
>>>Output
No data available
No valid email
Hello, Guest
Short-circuit evaluation is a powerful pattern. The first condition acts as a guard, preventing the second condition from being evaluated if it would cause an error. This is especially useful when checking if a value exists before accessing its properties.
Python Quiz

> An empty string is falsy in Python. Pick the operator that provides a fallback when the value is falsy, and the function that measures the result.

value = ""
fallback = "default"
result = value ___ fallback
print(___(result))
or
and
len
type
is

Conditionals in Pipelines

When processing collections of data, conditionals help you filter, categorize, and transform records based on their values. Here is an example that processes a list of transactions and applies different handling based on the transaction type and amount:
1transactions = [
2 {"id": 1, "type": "purchase", "amount": 150},
3 {"id": 2, "type": "refund", "amount": 25},
4 {"id": 3, "type": "purchase", "amount": 500},
5 {"id": 4, "type": "transfer", "amount": 1000},
6]
7
8purchases = refunds = other = 0
9large = []
10
11for tx in transactions:
12 if tx["type"] == "purchase":
13 purchases += tx["amount"]
14 elif tx["type"] == "refund":
15 refunds += tx["amount"]
16 else:
17 other += tx["amount"]
18
19 if tx["amount"] >= 200:
20 large.append(tx["id"])
21
22print(f"Purchases: {purchases}, Refunds: {refunds}, Other: {other}")
23print("Large transactions:", large)
>>>Output
Purchases: 650, Refunds: 25, Other: 1000
Large transactions: [3, 4]

This example combines if/elif/else for categorization with a separate if for flagging. Notice how the large transaction check is independent of the type categorization, so it uses a separate if statement rather than being nested inside the type checks.

Conditional Messages

A common task is building dynamic messages based on multiple conditions. This pattern appears in notifications, reports, and user interfaces:
1order = {"id": "A123", "status": "shipped", "items": 3, "eta": 2}
2
3status_text = {
4 "pending": "Awaiting",
5 "shipped": "On the way",
6 "delivered": "Delivered"
7}
8
9msg = f"Order {order['id']}: {status_text.get(order['status'], '?')}"
10msg += f" ({order['items']} item{'s' if order['items'] != 1 else ''})"
11
12if order["status"] == "shipped":
13 days = "day" if order["eta"] == 1 else "days"
14 msg += f" - ETA: {order['eta']} {days}"
15
16print(msg)
>>>Output
Order A123: On the way (3 items) - ETA: 2 days
This example shows how conditionals can progressively build up a complex output. Each condition adds or modifies part of the result. The nested conditions check secondary attributes only when they are relevant. This pattern of building up a message step by step is common in notification systems, logging frameworks, and report generators.

Common Mistakes

These are the most frequent errors when writing conditional statements. Understanding these pitfalls will help you avoid debugging headaches:
1# MISTAKE 1: Using = instead of ==
2x = 10
3# if x = 10: # WRONG - assignment
4# CORRECT - comparison
5if x == 10:
6 print("x equals 10")
7
8# MISTAKE 2: Forgetting the colon
9# if x == 10 # Missing colon - SyntaxError
10# Correct
11if x == 10:
12 print("Don't forget the colon!")
13
14# MISTAKE 3: Wrong indentation
15if x == 10:
16 print("This is indented correctly")
17 # print("...") # Error if not indented
18
19# MISTAKE 4: Comparing with "or" incorrectly
20day = "Monday"
21# if day == "Saturday" or "Sunday": # WRONG!
22# CORRECT
23if day == "Saturday" or day == "Sunday":
24 print("Weekend")
25else:
26 print("Weekday")
>>>Output
x equals 10
Don't forget the colon!
Weekday

The last mistake is particularly tricky. day == "Saturday" or "Sunday" evaluates as (day == "Saturday") or "Sunday". Since "Sunday" is a non-empty string (truthy), the condition is always True.

Keeping these best practices in mind will help you write conditionals that are both correct and easy for others to read:
Do
  • Use == for comparison, = for assignment
  • Always include the colon after conditions
  • Use elif for mutually exclusive branches
  • Compare each value explicitly with or
Don't
  • Nest more than 2-3 levels deep
  • Write "day == Sat or Sun" shorthand
  • Mix tabs and spaces for indentation
  • Forget to handle the else case
Control flow is what gives programs the ability to make decisions and respond to different conditions.
PUTTING IT ALL TOGETHER

> You are a data analyst at Shopify writing a Python script that categorizes every customer order into a priority tier based on order value and fulfillment status. Every order must reach exactly one tier, conditions must combine value and status together, and the script must process every record in sequence without gaps.

if statements check the first condition on each order so only orders that pass the initial test enter the premium branch.
if-else branching assigns a fallback tier when the premium condition is false, ensuring every order gets a label without unhandled gaps.
if-elif-else chains evaluate value thresholds in order from highest to lowest so orders are routed to exactly one of standard, priority, or premium.
Combining with and requires both high value and a fulfilled status to be true before the critical tier is assigned to an order.
KEY TAKEAWAYS
if executes code only when its condition is True; the indented block is skipped if False
else provides an alternative path that runs when the if condition is False
elif checks additional conditions in sequence; only the first True block executes
Use and when ALL conditions must be True; use or when ANY condition being True is sufficient
not inverts a boolean: True becomes False and vice versa
Nested conditionals create decision trees; keep nesting shallow for readability
Always use == for comparison, not = which is assignment
Order elif conditions from most specific to most general to avoid logic errors

Control Flow: Beginner

Making decisions in code

Category
Python
Difficulty
beginner
Duration
37 minutes
Challenges
0 hands-on challenges

Topics covered: The if Statement, Branching with if-else, Chaining if-elif-else, Combining with and/or, Execution Flow

Lesson Sections

  1. The if Statement (concepts: pyIfElse)

    Basic if Syntax Both indented print statements run because age is 21, which is greater than or equal to 18. The final print statement runs regardless of the condition because it is not indented under the if. When Conditions Are False When the condition evaluates to False, Python skips the entire indented block and continues with the next unindented line: Since 15 is not greater than 30, the condition is False and both indented lines are skipped. Only the final unindented line executes. Condition

  2. Branching with if-else

    Basic if-else Structure Since balance is 150, the condition is True, so the if block runs and the else block is skipped. Exactly one of the two blocks will always execute. The else Block Executes When the condition is False, the else block runs instead: Now balance is 50, so the condition is False. Python skips the if block entirely and executes the else block. The final print still runs because it is outside both blocks. Mutually Exclusive Paths With if-else, exactly one of the two code blocks

  3. Chaining if-elif-else

    Basic elif Syntax With a score of 85, the first condition (score >= 90) is False. Python moves to the first elif (score >= 80), which is True, so grade becomes "B". All remaining elif and else blocks are skipped. Order Matters Python evaluates conditions from top to bottom and stops at the first True condition. The order of your conditions is crucial: If you reversed the order and checked age < 65 first, everyone under 65 would be classified as "adult" regardless of whether they are children or

  4. Combining with and/or (concepts: pyBooleanOps)

    The and Operator The or Operator The not Operator Combining and, or, not You can combine logical operators to build complex conditions. Use parentheses to make the logic clear and control evaluation order: Parentheses can make compound conditions much easier to read. Wrapping related conditions in parentheses makes the grouping explicit and prevents subtle bugs from operator precedence surprises.

  5. Execution Flow

    Understanding how Python decides which lines to execute is fundamental to writing correct programs. In Python, indentation is not just for readability; it determines which code belongs together and when it runs. Indentation and Execution When you indent code under an if statement, you are telling Python: "only run these lines if the condition is True." The indentation level defines a block of code that executes together: The two indented print statements form a single block. They either both run