In this Python tutorial, we will learn about if-else statement, its syntax, and how to write an if-else statement with a condition using some general use cases as examples.
Python – If Else
Python If Else statement is used to conditionally choose between if block and else block for execution.
If the condition evaluates to True, then interpreter executes if-block. But, if the condition evaluates to False, then interpreter executes else-block.
Syntax
The syntax of if-else statement is
if <condition>:
statement(s)
else:
statement(s)
where condition
could be an expression that evaluates to a boolean value.
When interpreter enter if-else statement, it first evaluates the condition. If condition is True, statement(s) inside if block execute, or if condition is False, statements(s) inside else block execute.
Flowchart
The working of if-else statement in Python is shown in the following picture.
Examples
1. Check if Number is Even or Odd
In the following program, we write an if-else statement where the condition checks if given number is even.
Example.py
n = 4
if n%2 == 0:
print(f'{n} is even number.')
else:
print(f'{n} is odd number.')
Output
4 is even number.
Note : Observe the indentation and alignment of the statements inside the if-block and else-block. Unlike programming languages like Java or C programming, where the statements are enclosed in curly braces, Python considers the alignment of statements as block representation.
Now, let us take a value for n
, such that the condition becomes false.
Example.py
n = 3
if n%2 == 0:
print(f'{n} is even number.')
else:
print(f'{n} is odd number.')
Output
3 is odd number.
Since we have taken a value for n
such that the condition n%2 == 0
becomes False, the statement(s) inside else block were executed.
2. Program to choose a car based on money available
In the following program, we write an if-else statement to choose a car based on the money we have to spend.
Example.py
money = 125000
if money > 100000:
print("Buy Premium Car.")
else:
print("Buy Budget Car.")
Output
Buy Premium Car.
Conclusion
In this Python Tutorial, we have learnt if-else conditional statement, and how any statement in if or else block could be another if or if-else conditional statements.