Python If/Else
PythonDecision-making is the core of programming. Python's if/elif/else statements let your code make choices — like checking if a user is old enough to vote, or grading students based on marks. This lesson covers conditional logic, comparison operators, and the elegant one-liner ternary syntax.
Python uses if, elif, and else for decisions. Indentation (spaces) is mandatory!
Important
- Python uses
elif(not "else if") - Indentation (4 spaces) defines code blocks — no curly braces!
- Use
==for comparison,=for assignment
# Simple condition
age = 18
if age >= 18:
print("You can vote! ✅")
else:
print("Too young ❌")
# Multiple conditions
marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
else:
print("Grade: C")
# One-liner
status = "Adult" if age >= 18 else "Minor"
print(status)
Grade: A
Adult
Key Takeaways
-
Python uses
if,elif,elsefor branching logic - Indentation (4 spaces) defines code blocks — no curly braces needed
-
==compares values,=assigns values — don't confuse them -
One-liner:
x = "yes" if condition else "no"(ternary operator) -
You can chain multiple
elifblocks for complex decisions
Real-World Usage
Every app uses conditions: login systems check if passwords match, e-commerce sites apply discounts based on cart value, games decide if a player wins or loses, and ATMs check if you have sufficient balance. Mastering if/else is mastering logic itself.
Interview Questions — Python If/Else
5 questions commonly asked in interviews
Conditions allow a program to make decisions based on True or False expressions.
if statement executes code only if the condition is true.
elif allows checking multiple conditions sequentially.
else executes when all previous conditions are false.
A short form of if-else expression in one line.
Frequently Asked Questions
Common doubts about Python If/Else
Yes, using and, or, not operators.
Yes, indentation defines code blocks in Python.
Yes, one if can be inside another.
It checks equality of values.
== checks value equality, is checks object identity.
Test Your Knowledge
5 questions · Earn 50 XP
More on Python If/Else
Cheatsheet, tips, resources & what to learn next
Quick Cheatsheet
if x > 5:
print("Yes")
if x > 5:
print("Yes")
else:
print("No")
if x > 5:
pass
elif x == 5:
pass
print("Yes") if x > 5 else print("No")
if x > 5 and y < 10:
Pro Tips
Use proper indentation.
Avoid deep nested conditions.
Use elif for multiple conditions.
Use logical operators for complex checks.
Keep conditions readable.