if statements

CMPUT 175 Python Review: Decision-Making and Branching

Introduction to Conditionals

  • Emphasis on decision-making and branching in Python.

  • Known as "if statements."

  • Definition: Execute instructions if a condition is true.

Understanding Conditions

  • If Statements: Basic structure

    • Format: if condition: execute instructions

    • Execute when the condition is verified.

  • Else Clause: Executes if the condition is false.

    • Format: else: execute other instructions

    • Note: Else is optional.

Syntax of If Statements

  • Basic Syntax in Python:

    • `if condition:

      Indented code block`

    • Code after colon must be indented to signal execution when true.

Example Scenario: Store Receipt

  • Use Case: Print a receipt with discounts based on purchase amounts.

  • Rule: 5% discount for purchases $300 or more.

  • Variable: subtotal representing total purchase amount.

    • Example 1: subtotal = 80

      • Condition: subtotal > 300 → FALSE

    • Example 2: subtotal < 300

      • Condition: TRUE

    • Equality Check Mistake:

      • Incorrect: subtotal = 300 (assignment)

      • Correct: subtotal == 300 (comparison) → FALSE

    • Difference Check: subtotal != 300 → TRUE.

Using Conditions in Programs

  • Example Implementation:

    • Initialize discount = 0

    • Check: if subtotal >= 300:

      • Calculate: discount = subtotal * 0.05

      • Result for Subtotal 80: discount = 0

    • When subtotal = 400:

      • Discount calculation results in discount = 20

Else Clause for Conditional Logic

  • Complete implementation can look like:

    • if subtotal >= 300: discount = subtotal * 0.05 else: discount = 0

  • Verified Again with a subtotal = 400, yields $20 discount.

Control Flow in Python

  • Conditions can be any expressions returning TRUE or FALSE.

  • Logical Operators:

    • Negation: NOT

    • Conjunction: AND (both conditions must be true)

    • Disjunction: OR (at least one condition must be true)

  • Example Condition: if subtotal >= 100 and hasMembership:

  • Control flow example with multiple conditions:

    • Structure: if condition_1: instructions elif condition_2: instructions elif condition_3: instructions else: other instructions

Elif Clause

  • Elif: Represents "else if"

  • Additional discount tier: 2% for purchases between $100 and $300.

    • Example with subtotal = 150

      • Check if greater than 300 (FALSE), then check if greater than 100 (TRUE).

      • Resulting discount: 150 * 0.02 → $3

Summary

  • Reviewed control flow using if statements.

  • Discussed conditions as expressions that yield TRUE or FALSE.

  • Covered syntax and practical examples with the use of if, elif, and else clauses.