Conditional Statements in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will learn how to control the flow of your Python programs using conditional statements. We will begin by understanding the concept of sequential program execution and then introduce conditional logic, which enables programs to make decisions.

You will implement single and dual branch logic using if and if-else statements, and explore multi-branch logic with if-elif-else. The lab will also cover nested if statements, the pass statement, and introduce the match-case statement available in Python 3.10 and later versions. By the end of this lab, you will be able to write Python code that executes different blocks of instructions based on specific conditions.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Understand Sequential Flow and Introduce Conditional Logic

In this step, we will explore the concept of sequential flow in programming and introduce conditional logic, which allows programs to make decisions.

Sequential flow is the most basic type of program execution. Instructions are executed one after another, from top to bottom.

The lab environment has already created a file named sequential.py for you in the ~/project directory. Locate this file in the WebIDE's file explorer on the left panel and open it.

Add the following code to sequential.py:

print("First instruction")
print("Second instruction")
print("Third instruction")

Save the file. To run the script, open the integrated terminal in the WebIDE and execute the following command:

python ~/project/sequential.py

You will see the output printed in the exact order the print statements appear in the script:

First instruction
Second instruction
Third instruction

This demonstrates sequential flow. However, programs often need to behave differently based on certain conditions. This is where conditional logic comes in. The most fundamental conditional statement in Python is the if statement, which executes a block of code only if a specified condition is true.

The basic syntax of an if statement is:

if condition:
    ## Code to execute if the condition is true
    ## This block must be indented

Now, replace the content of sequential.py with the following code to include an if statement:

x = 10

print("Before the if statement")

if x > 5:
    print("x is greater than 5")

print("After the if statement")

Save the file and run it again:

python ~/project/sequential.py

The output will be:

Before the if statement
x is greater than 5
After the if statement

The condition x > 5 is true, so the indented code block inside the if statement is executed.

Now, let's see what happens when the condition is false. Modify sequential.py by changing the value of x to 3:

x = 3

print("Before the if statement")

if x > 5:
    print("x is greater than 5")

print("After the if statement")

Save the file and run it:

python ~/project/sequential.py

The output will be:

Before the if statement
After the if statement

This time, the condition x > 5 is false, so the code block inside the if statement is skipped. This simple example illustrates how the if statement introduces decision-making into our programs.

Implement Single and Dual Branch Logic with if and if-else

In this step, we will focus on implementing single and dual branch logic using the if and if-else statements.

The if statement allows for single-branch execution. Let's use the branching.py file that has been prepared for you. Open branching.py from the file explorer.

Add the following code to demonstrate a single-branch if statement:

score = 85

if score >= 70:
    print("Congratulations! You passed.")

print("End of program.")

Save the file and run it from the terminal:

python ~/project/branching.py

The output will be:

Congratulations! You passed.
End of program.

Since score is 85, the condition is true, and the congratulatory message is printed.

While if is useful, we often need to execute a different block of code when the condition is false. This is where the if-else statement comes in, providing dual-branch logic.

The syntax of an if-else statement is:

if condition:
    ## Code to execute if the condition is true
else:
    ## Code to execute if the condition is false

Let's modify branching.py to use an if-else statement. Replace the current content with the following:

score = 85

if score >= 70:
    print("Congratulations! You passed.")
else:
    print("Keep trying. You can do better.")

print("End of program.")

Save and run the script. With score as 85, the if block runs:

Congratulations! You passed.
End of program.

Now, to test the else block, modify the score to 65 in branching.py:

score = 65

if score >= 70:
    print("Congratulations! You passed.")
else:
    print("Keep trying. You can do better.")

print("End of program.")

Save the file and run it again:

python ~/project/branching.py

The output will now be:

Keep trying. You can do better.
End of program.

Since score is 65, the if condition is false, and the code in the else block is executed. The if-else statement is essential for handling two possible outcomes.

Implement Multi-Branch Logic with if-elif-else

In this step, we will learn how to handle situations with more than two possible outcomes using the if-elif-else statement, which provides multi-branch logic.

The if-elif-else structure checks conditions sequentially. If the if condition is false, it checks the first elif (short for "else if") condition, and so on. If no conditions are true, the else block is executed.

The basic syntax is:

if condition1:
    ## Executes if condition1 is true
elif condition2:
    ## Executes if condition1 is false and condition2 is true
else:
    ## Executes if all previous conditions are false

Open the multibranch.py file in the WebIDE. We will write a script to determine a letter grade based on a numerical score. Add the following code:

score = 88

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

print("Grading complete.")

Save the file and run it from the terminal:

python ~/project/multibranch.py

The output will be:

Grade: B
Grading complete.

The program checks score >= 90 (false), then score >= 80 (true), prints "Grade: B", and skips the rest of the chain.

Now, let's test the else block. Modify multibranch.py to set the score to 55:

score = 55

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

print("Grading complete.")

Save and run the script:

python ~/project/multibranch.py

The output will be:

Grade: F
Grading complete.

Finally, to prepare for the verification, change the score to 75 in multibranch.py:

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

print("Grading complete.")

Save and run the script one last time:

python ~/project/multibranch.py

The output will be:

Grade: C
Grading complete.

The if-elif-else structure is powerful for handling multiple distinct cases. Remember that only the code block for the first true condition is executed.

Explore Nested if Statements and the pass Statement

In this step, we will explore nested if statements, where one if statement is placed inside another, and also learn about the pass statement.

Nested if statements are useful when you need to check a condition, and if it is true, check another sub-condition.

Open the nested_if.py file in the WebIDE. Add the following code, which checks voting eligibility based on age and citizenship.

age = 20
is_citizen = True

if age >= 18:
    print("You are old enough to vote.")
    if is_citizen:
        print("You are also a citizen.")
        print("You are eligible to vote.")
    else:
        print("You are not a citizen.")
        print("You are not eligible to vote.")
else:
    print("You are not old enough to vote.")
    print("You are not eligible to vote.")

print("Voting eligibility check complete.")

Save the file and run it:

python ~/project/nested_if.py

The output will be:

You are old enough to vote.
You are also a citizen.
You are eligible to vote.
Voting eligibility check complete.

Both the outer condition (age >= 18) and the inner condition (is_citizen) are true.

Now, let's look at the pass statement. The pass statement is a null operation; nothing happens when it is executed. It is a useful placeholder when a statement is syntactically required, but you have not written the code for it yet.

Replace the content of nested_if.py with this example using pass:

age = 18

if age >= 18:
    pass ## Placeholder for future code
else:
    print("You are not old enough to vote.")

print("Check complete.")

Save and run the script:

python ~/project/nested_if.py

The output will be:

Check complete.

The if condition is true, so the pass statement is executed (doing nothing), and the else block is skipped.

Finally, to prepare for verification, modify nested_if.py to use the original logic but with an age that fails the first check.

age = 16
is_citizen = True

if age >= 18:
    print("You are old enough to vote.")
    if is_citizen:
        print("You are eligible to vote.")
    else:
        print("You are not eligible to vote.")
else:
    print("You are not old enough to vote.")
    print("You are not eligible to vote.")

print("Voting eligibility check complete.")

Save and run the script:

python ~/project/nested_if.py

The output will be:

You are not old enough to vote.
You are not eligible to vote.
Voting eligibility check complete.

Here, the outer if condition (age >= 18) is false, so the outer else block is executed, and the inner if-else structure is completely skipped.

Introduce match-case Statement (Python 3.10+)

In this step, we will explore the match-case statement, a feature introduced in Python 3.10 for structural pattern matching. It provides a readable alternative to if-elif-else chains for certain scenarios.

The match-case statement compares a value against a series of patterns and executes the code block for the first matching pattern.

The basic syntax is:

match value:
    case pattern1:
        ## Code for pattern1
    case pattern2:
        ## Code for pattern2
    case _:
        ## Code for no match (wildcard)

Open the match_case.py file in the WebIDE. Add the following code to print the day of the week based on a number.

day_number = 3

match day_number:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number")

print("Day check complete.")

Save the file and run it. The python command in this environment defaults to a compatible version.

python ~/project/match_case.py

The output will be:

Wednesday
Day check complete.

The value 3 matches case 3:, so "Wednesday" is printed.

Now, let's test the wildcard case. Modify match_case.py to use an invalid number:

day_number = 10

match day_number:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number")

print("Day check complete.")

Save and run the script:

python ~/project/match_case.py

The output will be:

Invalid day number
Day check complete.

Since 10 does not match any specific case, the wildcard case _: is matched.

Finally, to prepare for verification, change the day_number to 6 in match_case.py:

day_number = 6

match day_number:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number")

print("Day check complete.")

Save and run the script:

python ~/project/match_case.py

The output will be:

Saturday
Day check complete.

The match-case statement can be a cleaner way to handle multiple specific values compared to a long if-elif-else chain.

Summary

In this lab, you learned how to control the flow of your Python programs. You started with sequential program flow and then moved to conditional logic. You implemented single-branch logic with if, dual-branch logic with if-else, and multi-branch logic with if-elif-else. You also explored how to create more complex decision structures with nested if statements and how to use the pass statement as a code placeholder. Finally, you were introduced to the match-case statement as a modern alternative for pattern-based branching. You are now equipped to write Python programs that can make decisions and execute different code paths based on specific conditions.