Loading lesson...
Making decisions in code
Making decisions in code
Topics covered: The if Statement, Branching with if-else, Chaining if-elif-else, Combining with and/or, Execution Flow
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
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
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
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.
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