6  Control Structures: Conditional Statements

In programming, the ability to make decisions is crucial. Conditional statements allow a program to take different actions based on whether certain conditions are true or false. This chapter will introduce the concept of conditional statements in Python, illustrating their significance and how they can be utilized effectively in various programming scenarios.

6.1 The if Statement

The if statement is the most fundamental building block of conditional statements in Python. It allows the program to execute a block of code only if a specified condition is true. This section will delve deeper into the mechanics of the if statement, its syntax, and its practical applications.

Basic Syntax

The basic syntax of an if statement in Python is straightforward. It consists of the keyword if followed by a condition, a colon, and an indented block of code that will be executed if the condition is true.

Syntax:

if condition:
    statement(s)
  • condition: This is an expression that evaluates to either True or False.
  • statement(s): This is the block of code that will be executed if the condition evaluates to True.

The condition can be any expression that returns a Boolean value (i.e., True or False). If the condition evaluates to True, the indented block of code following the if statement is executed. If the condition evaluates to False, the block of code is skipped.

Example:

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

In this example, the condition x > 5 evaluates to True because 10 is greater than 5. Therefore, the code within the if block is executed, resulting in the output “x is greater than 5”.

Using Comparison Operators

The condition in an if statement often involves comparison operators. These operators compare two values and return True or False based on the comparison.

Common Comparison Operators:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

Examples:

# Equal to
x = 5
if x == 5:
    print("x is equal to 5")
x is equal to 5
# Not equal to
y = 10
if y != 5:
    print("y is not equal to 5")
y is not equal to 5
# Greater than
a = 7
if a > 3:
    print("a is greater than 3")
a is greater than 3
# Less than
b = 2
if b < 5:
    print("b is less than 5")
b is less than 5
# Greater than or equal to
c = 8
if c >= 8:
    print("c is greater than or equal to 8")
c is greater than or equal to 8
# Less than or equal to
d = 4
if d <= 4:
    print("d is less than or equal to 4")
d is less than or equal to 4

Combining Conditions with Logical Operators

Sometimes, you need to check multiple conditions simultaneously. Python provides logical operators to combine multiple conditions.

Logical Operators:

  • and: Returns True if both conditions are True
  • or: Returns True if at least one condition is True
  • not: Returns True if the condition is False

Examples:

# Using 'and' operator
x = 10
y = 20
if x > 5 and y > 15:
    print("Both conditions are true")
Both conditions are true
# Using 'or' operator
a = 5
b = 10
if a > 7 or b > 7:
    print("At least one condition is true")
At least one condition is true
# Using 'not' operator
c = 3
if not c > 5:
    print("c is not greater than 5")
c is not greater than 5

In the first example, the condition x > 5 and y > 15 evaluates to True because both 10 > 5 and 20 > 15 are true. Therefore, the code within the if block is executed, resulting in the output “Both conditions are true”.

In the second example, the condition a > 7 or b > 7 evaluates to True because 10 > 7 is true even though 5 > 7 is false. Hence, the output is “At least one condition is true”.

In the third example, the condition not c > 5 evaluates to True because c > 5 is false, and not operator negates it. Therefore, the output is “c is not greater than 5”.

Nested if Statements

You can nest if statements within other if statements to create more complex decision structures. This means placing one if statement inside another if statement’s block of code.

Example:

x = 15
if x > 10:
    print("x is greater than 10")
    if x > 20:
        print("x is also greater than 20")
x is greater than 10

In this example, the outer if statement checks if x is greater than 10. Since x is 15, the condition is true, and the code within the block is executed. Inside this block, there is another if statement that checks if x is greater than 20. Since 15 is not greater than 20, the block of the nested if statement is not executed.

6.2 The else Clause

The else clause in Python provides an alternative block of code that will execute if the condition in the if statement evaluates to False. This allows for a two-way decision-making process: if the condition is true, one set of statements will run, otherwise, a different set of statements will run.

Basic Syntax

The basic syntax for using the else clause follows directly after an if statement. The else clause must be at the same indentation level as the if statement, and its block of code must be indented further.

Syntax:

if condition:
    statement(s)
else:
    statement(s)
  • condition: This is an expression that evaluates to either True or False.
  • statement(s): This is the block of code that will be executed if the condition evaluates to False.

Example:

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")
x is not greater than 5

In this example, the condition x > 5 evaluates to False because 3 is not greater than 5. Therefore, the code within the else block is executed, resulting in the output “x is not greater than 5”.

Nested else Clauses

else clauses can be nested within other conditional blocks to create more complex decision structures. This is useful when the logic requires multiple levels of checks.

Example:

x = 15
if x > 10:
    print("x is greater than 10")
    if x > 20:
        print("x is also greater than 20")
    else:
        print("x is between 11 and 20")
else:
    print("x is 10 or less")
x is greater than 10
x is between 11 and 20

In this example, the outer if statement checks if x is greater than 10. Since x is 15, the condition is true, and the code within the block is executed. Inside this block, there is another if statement that checks if x is greater than 20. Since 15 is not greater than 20, the else block of the nested if statement is executed, resulting in the output “x is between 11 and 20”.

6.3 The elif Clause

In Python, the elif clause (short for “else if”) is used to check multiple conditions in a sequence. It allows you to add more than one conditional expression to an if statement, creating a chain of conditions that are evaluated in order. When one of these conditions evaluates to True, the corresponding block of code is executed, and the rest of the conditions are skipped.

Basic Syntax

The elif clause follows the if clause and is used to test additional conditions if the previous conditions were not true. You can have as many elif clauses as you need, and an optional else clause can be included at the end to handle cases where none of the if or elif conditions are true.

Syntax:

if condition1:
    statement(s)
elif condition2:
    statement(s)
elif condition3:
    statement(s)
  • condition1, condition2, condition3: These are expressions that evaluate to either True or False.
  • statement(s): These are the blocks of code that will be executed if the corresponding condition evaluates to True.

Using Multiple elif Clauses

The elif clause allows you to handle multiple potential cases in a clear and concise manner. The conditions are evaluated from top to bottom, and as soon as a True condition is found, the corresponding block of code is executed, and the rest of the conditions are skipped.

Example:

score = 85

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

In this example, the program checks the score and assigns a grade based on predefined ranges. The conditions are evaluated in order: score >= 90 is False, score >= 80 is True, so the code within the elif score >= 80 block is executed, resulting in the output “Grade: B”.

Combining elif with else

The else clause is optional but often used at the end of an if-elif chain to catch any cases that do not meet the previous conditions. This ensures that there is always a defined action for any possible input.

Example:

temperature = 75

if temperature > 85:
    print("It's hot outside.")
elif temperature > 65:
    print("The weather is nice.")
else:
    print("It's cold outside.")
The weather is nice.

In this example, the temperature is checked against three conditions. If the temperature is greater than 85, it prints “It’s hot outside.” If not, it checks if the temperature is greater than 65, printing “The weather is nice.” If neither condition is true, it defaults to printing “It’s cold outside.”

Practical Applications

Example: Speed Limit Checker

Let’s create a program that checks a car’s speed and prints a message based on the speed.

speed = 55

if speed > 80:
    print("You are speeding excessively.")
elif speed > 60:
    print("You are speeding.")
elif speed > 40:
    print("You are driving at a safe speed.")
else:
    print("You are driving below the speed limit.")
You are driving at a safe speed.

In this program, the speed is checked against multiple conditions to provide feedback on the driving speed. The conditions are evaluated in sequence, and the appropriate message is printed based on the speed.

Nested elif Clauses

Sometimes, you may need to nest elif clauses within other if-elif-else blocks to handle more complex decision-making processes.

Example: Admission Criteria

Let’s create a program that checks admission criteria based on age and test scores.

age = 18
test_score = 85

if age >= 18:
    if test_score >= 90:
        print("Admitted with a scholarship.")
    elif test_score >= 75:
        print("Admitted.")
    else:
        print("Not admitted due to low test score.")
else:
    print("Not admitted due to age requirement.")
Admitted.

In this example, the outer if statement checks if the age is 18 or older. If true, it enters a nested if-elif-else block that checks the test score. Depending on the test score, it prints the appropriate admission status. If the age condition is not met, it prints “Not admitted due to age requirement.”

The elif clause in Python is a powerful tool for handling multiple conditions in a clear and structured manner. By combining if, elif, and else clauses, you can create flexible decision-making processes in your programs. This allows your code to react dynamically to a wide range of inputs and conditions, making it more robust and versatile.

6.4 Conditional Expressions

Python also supports conditional expressions, which are a more concise way to write simple if-else statements.

Syntax:

value_if_true if condition else value_if_false

Example:

x = 5
result = "Positive" if x > 0 else "Non-positive"
print(result)
Positive

This example assigns the value “Positive” to the variable result if the condition x > 0 is True, otherwise it assigns “Non-positive”. The output will be “Positive”.

6.5 Exercises

Exercise 1: Odd or Even

Write a program that checks if a number is odd or even using conditionals.

Exercise 2: Age Group

Write a program that categorizes a person’s age group using only if and else statements.

Exercise 3: Positive, Negative, or Zero

Write a program that checks if a number is positive, negative, or zero. You must use at least one elif and one else statements.