If-else statement is similar to if statement, only difference is that an else block is added to it. The expression inside the parentheses is called a condition. The if statement checks whether the condition is true. If condition is true, the indented statement or statements after the if statement will execute. If the condition is false, indented statement or statements after the else statement will execute
Note: Make sure the fourth line starts at the left margin (with no indentation), but the fifth line must be indented again (preferably using the same indentation as line 3).
a = 20
if (a > 100):
print("a is greater than 100")
else:
print("a ")Execute the program, output will be:
a is smaller than 100
As you have understood, the else statement allows the program to define an alternative execution path between two possibilities.
We can improve this by using the elif statement (a combination of else and if):
a = 0
if a > 0:
print("a is greater than zero")
elif a < 0:
print("a is smaller than zero")
else:
print("a is equal to zero")On executing this program, the output will be:
a is equal to zero
The if statement used to check conditions can include the following comparison operators:
x == y → x is equal to yx != y → x is not equal to yx > y → x is greater than yx < y → x is less than yx >= y → x is greater than or equal to yx <= y → x is less than or equal to ya = 7
if (a % 2 == 0):
print("a is even")
else:
print("a is even")Note: The equality operator (
==) consists of two equals signs, not just one.
A single equals sign (=) is an assignment operator, not a comparison operator.
You will find the same syntax in other programming languages like Java and C++.
In the next article, we will learn about nested statement in Python.
No Comments