Chapter 5:Python Conditional Statements: if, else, and elif

Table of Contents

Introduction to Python if and else

In the last chapter, we learned different ways to use the print function. Now, let’s try to understand the use of conditional statements, if and else.

You can use the if statement when you want to execute a part of the code only if a certain condition is satisfied. Let’s go through a simple example to understand the syntax of the if statement:

In the above code, the print("Hello World!") statement will execute based on the value of the variable a". Here, the if condition is checking whether the value of a is less than 10. If that’s true, the print statement runs. So, if you run this code, you’ll see the output “Hello World!” You can try setting the value of the variable a" to a number like 15 (greater than 10), and you’ll notice that it doesn’t produce any output.

Understanding Python if Syntax:

Now, about the syntax. Unlike other programming languages that use curly brackets (or flower brackets), Python groups the code for an if condition using indentation. In the example above, notice that the print function isn’t written directly below the if condition. Instead, it’s indented after a few spaces. You can add one or more lines of code indented this way, and they will all be treated as part of the code under the if condition.

Try the code yourself:


Multiple Lines of Code in an if Statement

Let’s check an example with multiple lines of code in one if statement:

Notice that all the print functions are aligned with the same indentation to keep them under the same if condition. Try running the code after adding one or more spaces at the beginning of the second or third print function to see how Python raises an indentation error.

Try the code:


You can also place the code along with the if condition on the same line. For example:

If you have multiple lines of code that you want to keep under the if condition on the same line, use a semicolon (;) to separate them. For example:

As you may have already figured out, when we use an if condition, it expects two possible responses: True or False. In our previous examples, the expression a < 10 returned True because the value of the variable a" was set to 5. However, the same expression can return False if the value of a is not less than 10.


Using else with if:

Now, let’s try a code with the else part, which will be executed when the if expression is False:

In this code, the expression a < 10 will return False, so the else part will be executed. Therefore, the output will be “Python is Fun.”

You need to follow the same indentation rules for else as you do for if. You can have multiple lines of code in the else part, and just like with if, they should all be aligned with the same indentation.

Try the code yourself:

How does Python know when the “if" code block is finished?

Python uses indentation to define which lines belong to the if condition. All the lines that are indented after the if statement are considered part of that block. If you write any line of code directly below the if without indentation, it will be treated as outside the if block. It’s important to remember that at least one line of code must be indented under the if condition, or you’ll get an error.

Using the pass Statement

In some cases, you may not have any code to place under the indented block of an if or else statement. However, Python does not allow an empty if or else block without any code. In such situations, you can use the keyword pass with indentation to avoid a syntax error.

For example, if you don’t have anything to print or execute when the if condition is satisfied, you can use pass as shown below:

You can use the pass statement wherever an indented block is required, such as in a while loop, a function definition, a class definition, etc.


Checking Odd and Even Numbers with if and else

Here’s another classic example using if and else:

The above program will ask the user for a number and print whether it is odd or even. The expression a % 2 is used to get the remainder, and we are checking whether the remainder is 1 or 0 to determine if the given number is odd or even.

In Python, an expression used with if is considered True if it evaluates to any non-zero value, and False if it evaluates to 0, None, False, or an empty collection (like an empty string, list, or dictionary).

So, in this case, since a % 2 will return 1 when the variable a" is odd, you don’t necessarily need to write the full expression a % 2 == 1. Instead, just a % 2 is enough.

Try the code yourself:


Combining conditions with "and" and “or"

You can combine multiple expressions for evaluation using the and and or" operators.

For example:

In the first if statement, both conditions must be True for the print function to execute. In the second if statement, the print function will execute if one of the conditions is True.

Though we can check multiple conditions using the and" operator, there’s a limitation: you won’t be able to tell which specific expression returned False because there’s only one else statement for all the conditions.

If you need to check multiple conditions and want a separate else section for each, you can use a nested if structure instead. This way, each condition can have its own corresponding else block, allowing you to identify exactly which condition was not met.

Try the code yourself:


Nested if statements in Python

You can place one if statement inside the indented block of another if statement, which is called a nested if.

For example:

In the code editor below, experiment with different values for the variables a" and b". Change the values and see how the nested if statements behave. Pay attention to which blocks of code get executed depending on the conditions. This will help you understand how nested if statements work in Python.

For example: Set a = 40 and b = 120 to see how the else statements are triggered.


Using elif for Multiple Conditions

elif is short for “else if” and is used to check another condition if the if statement returns False. In an if-else structure, the else part gets executed if the if statement fails without checking any further conditions. However, in an if-elif structure, the elif part gets executed only after checking an additional condition if the if condition is False.

In this example, we’re using elif to check additional conditions after the initial if statement. If the if condition (score >= 90) is False, the program moves on to check if the score is greater than or equal to 80 with elif. If that condition is also False, it continues to check the next condition (score >= 70), and so on. The else block at the end ensures that if none of the previous conditions are met, it will print “Grade: F.” This way, elif allows us to handle multiple conditions in a clean and readable way

Note that only one of these blocks will execute, whichever condition becomes True first will trigger its corresponding block, and the rest of the statements below it will be ignored.

Try the code yourself:


Programming Exercises :

  1. Write a Python program to swap two numbers using a third variable.
  2. Write a Python program to swap two numbers without using a third variable.
  3. Write a Python program to read two numbers and find the sum of their cubes.
  4. Write a Python program to read three numbers, and if any two numbers are equal, print that number.
  5. Write a Python program to read three numbers and find the smallest among them.
  6. Write a Python program to read three numbers and print them in ascending order (without using the sort function).
  7. Write a Python program to read the radius of a circle and print the area.
  8. Write a Python program to read four numbers (representing the four octets of an IP) and check whether they are all in the range between 0 and 255.
  9. In the above program, if all numbers are in the valid range, print the class of IP.
  10. Write a Python program to read a number. If it is an even number, print the square of that number; otherwise, print the cube.
  11. Write a Python program to read three numbers and determine whether they form a valid triangle (sum of any two sides should be greater than the third side). If they form a valid triangle, print “Valid Triangle”; otherwise, print “Invalid Triangle.”
  12. Write a Python program to read a character from the user and check if it is a vowel or a consonant. If the character is a vowel, print “Vowel”; otherwise, print “Consonant.”
  13. Write a Python program to read a year and check if it is a leap year. If it is a leap year, print “Leap Year”; otherwise, print “Not a Leap Year.”
  14. Write a Python program to read an integer and print whether it is positive, negative, or zero.
  15. Write a Python program to read two numbers and check if one is a multiple of the other. If one is a multiple, print “Multiple”; otherwise, print “Not a Multiple.”
  16. Write a Python program to read a number and check if it is divisible by 5 and 11. If it is divisible by both, print “Divisible by 5 and 11”; otherwise, print “Not Divisible by 5 and 11.


We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.

Sajith Achipra has been a trainer and testing consultant at Zframez Technologies since 2009. With 15+ years of experience, he specializes in networking, Python, development, and testing. He conducts online courses to help students and professionals enhance their skills. You can reach him on WhatsApp at +91 8884 884 844 for your training and testing requirements.