The if-else statement in Python extends a simple condition into a full either-or decision, running one block or the other.
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++.
Once an if-else block is doing nothing more than choosing between two values, Python offers a shorter way to write the same logic on a single line: a conditional expression, often called Python’s ternary operator because it works on three parts at once. Its syntax reverses the order you’d expect from a normal if statement – the result comes first, the condition second: value_if_true if condition else value_if_false. So a block like:
a = 20
if a > 100:
result = "a is greater than 100"
else:
result = "a is 100 or less"
print(result)
can be written in a single line as:
a = 20 result = "a is greater than 100" if a > 100 else "a is 100 or less" print(result)
Both versions do exactly the same thing and produce the same output. The one-line form is best kept for genuinely simple, two-outcome decisions like this one; stacking several conditional expressions together, or nesting one inside another, tends to produce code that’s harder to read than the ordinary if-else block it was meant to shorten.
In the next article, we will learn about nested statement in Python.
No Comments