Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Conditional Logic: If, Elif, and Else

Recommended resources

Welcome to your fourth lesson. In our last session, we tackled the essential skill of debugging, learning how to read tracebacks and use print() statements to find and fix errors in our code. Those skills are about to become even more valuable.

Today, we'll explore how to give our programs the ability to make decisions. This lesson focuses on conditional statements, which allow your code to follow different paths depending on whether certain conditions are met. This is how programs become responsive and "intelligent." Your work in administration and caregiving is full of conditional logic: if a patient's temperature is above 37.5°C, you take one action; else, you take another. We will be teaching Python to do the very same thing.

By the end of this lesson, you will be able to use if, elif, and else statements to control the flow of your programs.

The Anatomy of a Decision: if, elif, and else

At its core, a computer program executes instructions sequentially, one after the other. Conditional statements break this rigid flow, allowing the program to choose which block of code to execute next.

The three keywords you'll use to build this logic are:

  • if: This starts the decision. The code inside an if block only runs if the specified condition is true.
  • elif: Short for "else if," this allows you to check another condition if the previous if (or elif) condition was false. You can have as many elif blocks as you need.
  • else: This is the catch-all. The code inside the else block runs only if all preceding if and elif conditions were false.

The following image shows a simple but very common use case: assigning grades based on a mark.

This example demonstrates a basic `if/elif/else` structure to categorize an exam mark as 'Excellent', 'Pass', or 'Fail'.

This structure is a powerful way to handle multiple mutually exclusive outcomes. Let's break down the syntax and rules for each part.


Building Conditional Blocks

The best way to understand these statements is to see them in action, from the simplest form to the full structure. The video below from Programming with Mosh provides a clear, step-by-step walkthrough.

Control Flow in Python - If Elif Else Statements

This video explains the fundamental syntax of conditional statements in Python. Pay close attention to the concepts of conditions, colons, and especially indentation.

Watch the following two segments: First, focus on the basic if statement structure and the critical role of indentation from the beginning of the video. Next, see how elif and else are added to handle multiple and alternative paths in the segment from elif and else.

As you saw in the video, the structure is always:

  1. A keyword (if, elif, or else).
  2. A condition (for if and elif), which is an expression that evaluates to True or False.
  3. A colon (:).
  4. An indented block of code that will be executed if the condition is met.

The DataCamp article, "if…elif…else in Python Tutorial," offers a concise written summary of these concepts. You can refer to it now or bookmark it for future review.

if…elif…else in Python Tutorial

This article provides clear examples for each part of the conditional structure.

You can quickly read through the sections on the if condition, the if-else condition, and the if-elif-else condition to reinforce your understanding.


Crafting Complex Conditions

Simple checks like temperature > 30 are useful, but real-world problems often require more complex logic. You can combine multiple conditions using logical operators.

  • and: True only if both conditions are true. (e.g., has_high_income and has_good_credit)
  • or: True if at least one of the conditions is true. (e.g., is_weekend or is_holiday)
  • not: Inverts a boolean value. True becomes False, and False becomes True. (e.g., not is_a_student)

The Programming with Mosh video has an excellent, practical example of building a loan eligibility checker using these operators.

Control Flow in Python - If Elif Else Statements

This segment demonstrates how to build more realistic and complex conditions for your if statements.

Watch the section from logical operators to see how and, or, and not are used. Then, watch the short clip on chaining comparison operators, which shows a cleaner way to check if a value falls within a range (e.g., 18 <= age < 65).


Hands-On Practice

Now it's time to write some code. This is where the concepts will truly solidify. Please open a new Jupyter Notebook for these exercises. For each problem, read the description, try to write the code yourself, and then compare your work with the provided solution.

The following exercises are from the "10 if-else Practice Problems in Python" article on LearnPython.com.

Exercise 1: Making a Decision

Problem: Write a program that asks for a user's answer to a trivia question. If they answer 'n', they are correct. If they answer 'y', they are wrong. For any other input, the program should state that it doesn't understand the answer.

  • Question: "Is Sydney the capital of Australia?"
  • If input is 'n': print Correct!
  • If input is 'y': print Wrong! Canberra is the capital!
  • If input is anything else: print I do not understand your answer!

Try to solve this in your notebook now.

Once you've attempted it, review the solution and explanation below.

10 if-else Practice Problems in Python

This exercise is a perfect demonstration of the if-elif-else structure.

Read through this problem and its solution to see how it handles the three possible cases.

Exercise 2: Nested Logic

Sometimes you need to make a decision within another decision. This is called nested logic.

Problem: Write a program that asks the user for a year and determines if it is a leap year. The rules for a leap year are:

  • A year is a leap year if it is divisible by 4...
  • ...UNLESS it is also divisible by 100 but NOT divisible by 400.

For example:

  • 2000 is a leap year (divisible by 4, 100, and 400).
  • 1900 is NOT a leap year (divisible by 4 and 100, but not 400).
  • 2024 is a leap year (divisible by 4, but not 100).
  • 2023 is NOT a leap year (not divisible by 4).

Hint: You will need the modulo operator (%), which gives the remainder of a division. year % 4 == 0 means "the year is perfectly divisible by 4."

Attempt to build the nested if statements for this logic in your notebook.

After you've given it a try, examine the solution below.

10 if-else Practice Problems in Python

This problem is a classic example of nested if statements.

Review the solution and explanation to understand how the conditions are checked one inside the other.

Exercise 3: Conditionals in Functions

Conditional statements are often used inside functions to return different results based on the input.

Problem: Write a function named return_bigger(a, b) that takes two numbers as arguments.

  • It should return the larger of the two numbers.
  • If the numbers are equal, it should return 0.

Write this function in your notebook and test it with a few examples, like return_bigger(10, 5) and return_bigger(7, 7).

Once you are done, check your work against the official solution.

10 if-else Practice Problems in Python

This exercise shows how if statements can control the return value of a function.

Read the short section for this final problem.


Conclusion

You have now learned one of the most fundamental concepts in programming: controlling your program's flow with conditional logic. You can now write code that responds dynamically to different inputs and situations.

Here are the key takeaways from this lesson:

  • Conditional logic is built using if, elif, and else statements.
  • Each conditional statement checks a boolean expression and executes an indented code block if the condition is True.
  • The if statement starts the block, elif checks additional conditions, and else acts as a default case.
  • You can create complex conditions by combining boolean variables and comparison checks with logical operators like and, or, and not.

In our next lesson, we will introduce loops. While conditionals allow you to run a block of code once based on a condition, loops will empower you to run a block of code repeatedly. When combined, conditionals and loops form the backbone of countless algorithms, from simple data processing tasks to the complex logic inside the AI models you aim to build.