Conditional Statements in Python
Introduction
In real life, we make decisions every day:
- If it rains, take an umbrella.
- If you pass the exam, you get a certificate.
Similarly, in Python, conditional statements are used to make decisions and execute different blocks of code based on conditions.
Definition
Conditional statements in Python allow a program to execute specific code only when a given condition is true. If the condition is false, another block of code can be executed.
Python uses the following conditional statements:
ifif-elseif-elif-elsenested if
Syntax / Structure
Basic if Syntax
if condition:
statement(s)
if-else Syntax
if condition:
statement(s)
else:
statement(s)
if-elif-else Syntax
if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)
Important:
- Python uses indentation (spaces) instead of brackets
{ }. - Indentation defines the code block.
Types of Conditional Statements in Python
- if Statement – Executes code only if the condition is true.
- if-else Statement – Executes one block if true, another if false.
- if-elif-else Statement – Used to check multiple conditions.
- Nested if Statement – An if statement inside another if.
Examples
Example 1: if Statement
age = 18
if age >= 18:
print("You are eligible to vote")
Example 2: if-else Statement
num = 5
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Example 3: if-elif-else Statement
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Example 4: Nested if Statement
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login successful")
else:
print("Wrong password")
else:
print("Wrong username")
Example Explanation
Example 1 Explanation
- The condition
age >= 18is checked. - If it is True, Python prints the message.
- If it is False, nothing happens.
Example 2 Explanation
%checks the remainder.- If remainder is 0, the number is even.
- Otherwise, it is odd.
Example 3 Explanation
- Python checks conditions from top to bottom.
- The first true condition is executed.
- Remaining conditions are skipped.
Example 4 Explanation
- First, Python checks the username.
- If correct, it checks the password.
- This is called nested decision-making.
Key Points / Notes
- Comparison operators:
==,!=,>,<,>=,<= - Logical operators:
and,or,not - Indentation is mandatory in Python.
- Only one block executes in an
if-elif-elsestructure.
Common Mistakes
- ❌ Using
=instead of== - ❌ Forgetting indentation
- ❌ Writing conditions without
:
Conclusion / Summary
- Conditional statements control the flow of execution.
- Python provides
if,else,elif, and nestedif. - They make programs smart and decision-based.
- Mastering conditions is essential for real-world programs.