Table of Contents
- Introduction to Python `if` and `else`
- Understanding Python `if` Syntax
- Multiple Lines of Code in an `if` Statement
- Using `else` with `if`
- How does Python know when the `if` code block is finished?
- Using the `pass` Statement
- Checking Odd and Even Numbers with `if` and `else`
- Combining conditions with `and` and `or`
- Nested `if` statements in Python
- Using `elif` for Multiple Conditions
- Programming Exercises
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:
a = 5
if a < 10:
print("Hello World!")
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:
a = 5
if a < 10:
print("Hello World!")
print("Python is Fun!")
print("Keep Coding!")
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:
a = 5
if a < 10: print("Hello World!")
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:
a = 5
if a < 10: print("Hello World!"); print("Python is Fun!"); print("Keep Coding!")
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
:
a = 50
if a < 10:
print("Hello World")
else:
print("Python is Fun")
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:
a = 50
if a < 10:
pass
else:
print("Hello World")
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
:
a = int(input("Enter a number: "))
if a % 2 == 1:
print(f"{a} is an odd number")
else:
print(f"{a} is an even number")
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:
a, b = 10, 20
if a < 50 and b < 100:
print("Both the conditions are True")
if a < 5 or b < 100:
print("Either both or one of the conditions is True")
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:
a, b = 10, 20
if a < 50:
if b < 100:
print("a is less than 50 and b is less than 100")
else:
print("a is less than 50 but b is not less than 100")
else:
print("a is not less than 50")
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
.
score = int(input("Enter the student's score: "))
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")
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 :
- Write a Python program to swap two numbers using a third variable.
- Write a Python program to swap two numbers without using a third variable.
- Write a Python program to read two numbers and find the sum of their cubes.
- Write a Python program to read three numbers, and if any two numbers are equal, print that number.
- Write a Python program to read three numbers and find the smallest among them.
- Write a Python program to read three numbers and print them in ascending order (without using the sort function).
- Write a Python program to read the radius of a circle and print the area.
- 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.
- In the above program, if all numbers are in the valid range, print the class of IP.
- Write a Python program to read a number. If it is an even number, print the square of that number; otherwise, print the cube.
- 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.”
- 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.”
- 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.”
- Write a Python program to read an integer and print whether it is positive, negative, or zero.
- 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.”
- 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.
About The Author:
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.