Week 4: Guiding Your Code with Conditional Logic

Learn how to make your Python programs make decisions using `if`, `elif`, and `else` statements.

Explore Chapter 4

Chapter 4: Making Decisions with `if`, `elif`, and `else`

Understanding Conditional Logic.

Conditional logic is a fundamental concept in programming that allows your program to execute different blocks of code based on whether certain conditions are true or false. This enables your programs to be more dynamic and responsive to different situations.

In Python, we use the `if`, `elif` (short for "else if"), and `else` statements to implement conditional logic. These keywords allow you to create control flow structures that branch based on the evaluation of boolean expressions (expressions that result in either `True` or `False`).

Think of it like making choices in real life. "If it's raining, I'll take an umbrella. Otherwise, I won't." Programming conditionals work in a similar way, allowing your code to take different paths depending on whether a condition is met.

`if` Statements: Executing Code Based on a Condition.

The `if` statement is the most basic form of conditional statement. It allows you to execute a block of code only if a specified condition is true.

Syntax

if condition:
    # Code to be executed if the condition is True
    statement1
    statement2
    # ... more statements
  • The `if` keyword is followed by a condition, which is an expression that evaluates to either `True` or `False`.
  • The condition is followed by a colon `:`.
  • The code block that should be executed if the condition is `True` is indented under the `if` statement. Indentation is crucial in Python to define the scope of the code block.

Example

age = 20
if age >= 18:
    print("You are eligible to vote.")

In this example, the message "You are eligible to vote." will be printed only if the value of the `age` variable is 18 or greater.

`elif` (else if) Statements: Checking Multiple Conditions.

The `elif` statement allows you to check multiple conditions in sequence. It is used after an `if` statement and before an optional `else` statement. The `elif` condition is checked only if the preceding `if` (or another `elif`) condition was false.

Syntax

if condition1:
    # Code to be executed if condition1 is True
elif condition2:
    # Code to be executed if condition1 is False AND condition2 is True
elif condition3:
    # Code to be executed if condition1 and condition2 are False AND condition3 is True
# ... more elif statements
  • You can have multiple `elif` statements after an `if` statement.
  • The conditions in the `elif` statements are evaluated in order. As soon as one `elif` condition evaluates to `True`, its corresponding code block is executed, and the rest of the `elif` and `else` blocks are skipped.

Example

grade = 85
if grade >= 90:
    print("Excellent!")
elif grade >= 80:
    print("Very good.")
elif grade >= 70:
    print("Good.")
elif grade >= 60:
    print("Pass.")
else:
    print("Fail.")

In this example, only one message will be printed based on the value of the `grade` variable.

`else` Statements: Providing a Default Action.

The `else` statement provides a block of code that is executed if none of the preceding `if` or `elif` conditions were true. It is always the last part of an `if-elif-else` structure.

Syntax

if condition:
    # Code to be executed if condition is True
else:
    # Code to be executed if the condition is False
if condition1:
    # Code for condition1 being True
elif condition2:
    # Code for condition1 being False and condition2 being True
else:
    # Code to be executed if both condition1 and condition2 are False
  • An `else` statement is optional and can appear at most once at the end of an `if-elif` sequence.
  • The `else` block does not have a condition; it is executed by default if no other condition was met.

Example

number = 7
if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

In this case, since 7 is not divisible by 2, the `else` block will be executed.

Nested `if` Statements: Conditions within Conditions.

You can also have `if`, `elif`, and `else` statements inside other `if` statements. This is known as nesting conditional statements. Nesting allows you to create more complex decision-making structures.

Syntax

if outer_condition:
    print("Outer condition is True.")
    if inner_condition:
        print("Inner condition is also True.")
    else:
        print("Inner condition is False.")
else:
    print("Outer condition is False.")
  • Be careful with indentation when nesting `if` statements, as it determines which block of code belongs to which condition.
  • Excessive nesting can make your code harder to read and understand. In some cases, you might be able to simplify nested conditions using logical operators (`and`, `or`).

Example

age = 25
country = "USA"

if country == "USA":
    if age >= 18:
        print("You are eligible to vote in the USA.")
    else:
        print("You are not yet eligible to vote in the USA.")
else:
    print("Voting eligibility rules vary by country.")

This example first checks if the `country` is "USA", and then, if it is, it checks the `age` to determine voting eligibility.

Syllabus