✍️Introduction
In programming, we often need to make decisions.
For example:
• If marks ≥ 40 → Pass
• Else → Fail
Python uses conditional statements to make such decisions.
In this article, you will learn:
- What conditional statements are
- if, elif, else statements
- Simple and clear examples
What are Conditional Statements in Python?
Conditional statements allow a program to execute different code blocks based on conditions.
Python checks the condition:
• If True → code runs
• If False → code is skipped
1️⃣ if Statement
The if statement executes code only if the condition is true.
Syntax:
if condition:
statement
Example:
age = 18
if age >= 18:
print("You are eligible to vote")
2️⃣ if–else Statement
The else block runs when the if condition is false.
Syntax:
if condition:
statement
else:
statement
Example:
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")
3️⃣ if–elif–else Statement
Used when there are multiple conditions.
Syntax:
if condition1:
statement
elif condition2:
statement
else:
statement
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
4️⃣ Nested if Statement
An if inside another if is called a nested if.
Example:
age = 20
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
Comparison Operators Used in Conditions
Operator Meaning
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Logical Operators in Conditions
Operator Meaning
and Both conditions true
or Any one condition true
not Reverse result
Example:
age = 25
if age > 18 and age < 60:
print("Working age group")
❌ Common Mistakes by Beginners
❌ Forgetting colon :
❌ Wrong indentation
❌ Using = instead of ==
Correct example:
if a == 10:
print("Correct")
🎯 Why Conditional Statements are Important?
- Used in decision making
- Core concept of programming
- Important for exams & interviews
- Used in real-life applications
Real-Life Example
balance = 500
if balance >= 1000:
print("Withdraw allowed")
else:
print("Insufficient balance")
Conclusion
Python conditional statements help programs think and decide.
Understanding if, elif, and else is very important for writing logical programs.
Practice more examples to master this topic.
💬 Let’s Interact!
What will be the output of this code?
x = 10
if x > 5:
print("Yes")
else:
print("No")
Comment your answer 👇😊
📌 Related Articles:
Comments
Post a Comment