Skip to main content
Back

Decision Structures and Conditional Statements in Python

Study Guide - Smart Notes

Tailored notes based on your materials, expanded with key definitions, examples, and context.

Structure of Programs

Main Program Structures

Python programs are typically organized using three fundamental control structures: sequence, decision, and repetition. Understanding these structures is essential for designing logical and efficient code.

  • Sequence Structure: Executes statements one after another in order.

  • Decision Structure: Allows branching based on conditions (using if, else, elif).

  • Repetition Structure: Enables repeated execution of code blocks (using while and for loops).

Example: A flowchart for a decision structure might check if a condition is true, then execute one block of code, otherwise execute another.

Decision Structures

Introduction to Decision Structures

Decision structures, also known as branching structures, allow a program to choose between alternative courses of action based on whether a condition is true or false. This is fundamental for implementing logic in programs.

  • True (if) branch: Executes if the condition is true.

  • False (else) branch: Executes if the condition is false.

Example: Determining the actual floor in a building, skipping floor 13:

if floor > 13: actualFloor = floor - 1 else: actualFloor = floor

Form of if-else Statements

Syntax and Structure

The if-else statement in Python allows conditional execution of code blocks. The general form is:

if condition: statements1 else: statements2

  • Condition: An expression that evaluates to True or False.

  • Relational operators: <, >, <=, >=, ==, !=

  • Colon: Indicates the start of a compound statement.

  • Indentation: Used to define blocks of code in Python.

Example: Skipping floor 13 in a building:

if floor > 13: actualFloor = floor - 1 else: actualFloor = floor

if-else Statements

Finding the Larger of Two Numbers

The if-else statement can be used to compare two values and determine which is larger.

  • Prompt the user for two numbers.

  • Compare the numbers using an if statement.

  • Assign the larger value to a variable and display it.

Example:

num1 = eval(input("Enter the first number: ")) num2 = eval(input("Enter the second number: ")) if num2 > num1: largerValue = num2 else: largerValue = num1 print("The larger value is", str(largerValue) + ".")

Output Example:

Enter the first number: 56 Enter the second number: 67 The larger value is 67.

Practice: Discount Calculation

Conditional Discount Application

Conditional statements can be used to apply different discounts based on the price of an item.

  • If the price is less than $128, apply an 8% discount.

  • If the price is at least $128, apply a 10% discount.

Example: Calculating the discounted price for a bookstore sale.

if price < 128: discounted_price = price * 0.92 else: discounted_price = price * 0.90 print("Your price is $", discounted_price)

Good Programming Practice

Avoiding Code Duplication

When the same code appears in both branches of an if-else statement, it should be moved outside the conditional to avoid duplication and improve readability.

  • Write shared code after the if-else block.

Example:

if floor > 13: actualFloor = floor - 1 else: actualFloor = floor print("Actual floor:", actualFloor)

if Statements Without else

Omitting the else Clause

The else part of an if-else statement is optional. If omitted, and the condition is false, execution continues with the next line after the if block.

  • Use when only one branch of code needs to be executed conditionally.

Example:

if score >= 60: print("You passed!") # No else needed if no action is required for failing scores.

Assignment vs. Equality Testing

Distinguishing = and ==

In Python, = is used for assignment, while == is used for equality testing.

  • Assignment: floor = 13 sets the value of floor to 13.

  • Equality Testing: floor == 13 checks if floor is equal to 13.

Common Error: Floating Point Comparison

Precision Issues

Floating-point numbers have limited precision, which can lead to roundoff errors in calculations. When comparing floating-point numbers, these errors must be considered.

  • Use a tolerance when comparing floats.

Example:

if abs(a - b) < 1e-9: print("a and b are approximately equal")

Nested if-else Statements

Implementing Multiple Levels of Decision

Nested if-else statements allow for more complex decision-making by placing one if or if-else statement inside another.

  • Useful for handling multiple conditions and sub-conditions.

Example: Hotel pricing for platinum members:

is_platinum = input("Are you a platinum member (Y/N)?: ") nights = int(input("How many nights do you stay?: ")) if is_platinum == "Y": if nights >= 5: price = (nights - 1) * 90 else: price = nights * 90 else: price = nights * 100 print(f"Total amount is ${price}. Thanks for choosing us.")

Multiple Alternatives: elif Clause

Handling Multiple Conditions

The elif clause allows checking more than two possible alternatives. As soon as one condition is true, its block is executed and no further conditions are checked.

  • Use elif for multi-way branching.

Example: Earthquake effect based on Richter scale:

richter = eval(input("Enter measurement of the earthquake: ")) if richter >= 7.0: print("Most structures fall") elif richter >= 6.0: print("Many buildings destroyed") elif richter >= 4.5: print("Damage to poorly constructed buildings") else: print("No destruction of buildings")

Richter Scale

Effect

≥ 7.0

Most structures fall

6.0 - 6.99

Many buildings destroyed

4.5 - 5.99

Damage to poorly constructed buildings

< 4.5

No destruction of buildings

Problem Solving: Test Cases

Testing Decision Points

To ensure complete coverage of all decision points in your code, design test cases that cover each branch, including boundary cases and zero values.

  • Test each branch of your code.

  • Estimate time for design, coding, and debugging.

  • Leave extra time for unexpected problems.

Input Validation

Ensuring Valid User Input

Accepting user input can be risky. Input validation using if-elif-else statements and string methods like isdigit() helps guard against improper input.

  • Check if input is a digit before evaluating.

  • Provide feedback for invalid input.

Example:

num1 = input("Enter first number: ") num2 = input("Enter second number: ") if num1.isdigit() and num2.isdigit(): num1 = eval(num1) num2 = eval(num2) maximum = num1 if num2 > num1: maximum = num2 print(f"The largest value is {maximum}.") else: print("One of the inputs is not valid.")

Comments and Readability

Best Practices for Writing Conditional Statements

  • Use if boolExp: instead of if boolExp == True:

  • Use if not boolExp: instead of if boolExp == False:

  • Use indentation to mark blocks of code for readability.

  • Compound statements consist of a header and an indented block.

  • if, else, and elif are reserved words in Python.

Additional info: The notes mention that other compound statements, such as while and for loops, will be discussed in future lectures.

Pearson Logo

Study Prep