Learn what an if statement in Python is, its types, syntax, examples, and programs. A simple, beginner-friendly guide to understand Python if statements easily.
In programming, a computer often needs to make decisions. Based on certain conditions, it decides which instructions should be executed next. Decision-making statements help a program choose different actions according to different situations.
Python provides the following decision-making statements:
- if statement
- if…else statement
- if…elif…else statement
- Nested if statement
if Statement
The if statement checks a condition. If the condition is True, the statements inside the if block are executed. If the condition is False, the statements are skipped.
Syntax
if condition:
statement(s)
Example
num = int(input(“Enter a number”))
if num > 0:
print(“Positive Number”)
print(“Program Ended”)
Output
Positive Number
Program Ended
Remember: The statements inside an if block must be indented.
Note:
Indentation in Python
- Python uses indentation to define blocks of code and nested block structures.
- Indentation refers to the spaces or tabs added at the beginning of a statement.
- Python strictly checks indentation, and incorrect indentation results in a syntax error.
if…else Statement
Sometimes we want one action to happen when a condition is True and another action when it is False. In such cases, we use the if…else statement.
Syntax
if condition:
statement(s)
else:
statement(s)
Example
age = int(input(“Enter your age”))
if age >= 18:
print(“You can vote”)
else:
print(“You cannot vote”)
Output
You cannot vote
if…elif…else Statement
The if…elif statement is used when multiple conditions need to be checked and a program has to choose one option from several alternatives.
How it Works
- The if condition is checked first.
- If it is True, its block is executed.
- If it is False, Python checks the next elif condition.
- This process continues until a condition becomes True.
- If none of the conditions are true, the else block is executed.
- Python executes only the first matching block and ignores the remaining conditions.
Syntax
if condition1:
statement(s)
elif condition2:
statement(s)
elif condition3:
statement(s)
else:
statement(s)
Example
marks = int(input(“Enter your marks”))
if marks >= 90:
print(“Grade A+”)
elif marks >= 75:
print(“Grade A”)
else:
print(“Grade B”)
Output
Grade A
Explanation
The first condition is False, but the second condition is True, so the elif block is executed.


