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
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):
When Conditions Are False
Conditions and Booleans
The condition in an if statement must evaluate to a boolean value (True or False). Comparison operators naturally produce boolean results:
Notice that equality comparison uses == (two equals signs), not = (single equals, which is assignment). This is a common source of errors.
Collection Conditions
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:
> 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.
Branching with if-else
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:
The else Block Executes
Mutually Exclusive Paths
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
> 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.
Chaining if-elif-else
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:
Order Matters
Multiple elif Clauses
elif vs Multiple if
- Exactly ONE block executes
- Stops at first true condition
- Mutually exclusive branches
- More efficient
- MULTIPLE blocks can execute
- Checks ALL conditions
- Independent conditions
- Use when conditions overlap
> 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
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:
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:
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:
Combining and, or, not
Operator precedence: not is evaluated first, then and, then or. When in doubt, use parentheses to make your intent explicit.
> 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.
> 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)
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
Trace how Python picks which lines run
Indentation and Execution
Nested Blocks
Nesting vs Combining
Nested conditionals can often be rewritten using and. Choose based on whether you need different else blocks at each level:
Data Validation Patterns
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:
> 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))
Conditionals in Pipelines
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
Common Mistakes
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.
- Use == for comparison, = for assignment
- Always include the colon after conditions
- Use elif for mutually exclusive branches
- Compare each value explicitly with or
- 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
> 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.and requires both high value and a fulfilled status to be true before the critical tier is assigned to an order.if executes code only when its condition is True; the indented block is skipped if Falseelse provides an alternative path that runs when the if condition is Falseelif checks additional conditions in sequence; only the first True block executesand when ALL conditions must be True; use or when ANY condition being True is sufficientnot inverts a boolean: True becomes False and vice versa== for comparison, not = which is assignmentControl 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
- 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
- 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
- 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
- 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.
- 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