A conditional statement allows a Python program to make decisions based on whether a condition is True or False.
In real programs, we constantly need to make decisions:
- If the user is logged in → show the dashboard.
- If the age is 18 or above → allow registration.
- If marks are above 40 → student passes.
- If the password is incorrect → reject login.
- If the price is above a certain amount → apply a discount.
Python mainly provides:
if
elif
elseConditional statements work closely with comparison operators and logical operators.
1. The if Statement
The if statement executes a block of code only when its condition is True.
Syntax
if condition:
# code to executeExample:
age = 25
if age >= 18:
print("You are eligible.")Output:
You are eligible.Because:
age >= 18is True.
2. Understanding the Colon :
Python uses a colon after the condition:
if age >= 18:The colon tells Python that a new block of code is beginning.
For example:
if age >= 18:
print("Eligible")The code after the colon must belong to the if block.
3. Indentation
Python uses indentation to define blocks of code.
Correct:
age = 25
if age >= 18:
print("You are an adult.")
print("You can apply.")Both print() statements belong to the if block.
Incorrect:
if age >= 18:
print("You are an adult.")This causes an IndentationError.
Recommended style
Use 4 spaces for indentation.
if condition:
statement4. Condition Must Produce a Boolean Result
A condition normally evaluates to:
Trueor:
FalseExample:
age = 25
print(age >= 18)Output:
TrueWe can use that condition directly:
if age >= 18:
print("Adult")5. Using == in Conditions
The equality operator == is commonly used in conditions.
name = "Raj"
if name == "Raj":
print("Welcome Raj")Output:
Welcome RajRemember:
=means assignment.
==means comparison.
6. Using Comparison Operators
All comparison operators can be used inside conditions.
age = 25
if age > 18:
print("Age is greater than 18")
if age == 25:
print("Age is 25")
if age != 30:
print("Age is not 30")Common operators:
==
!=
>
<
>=
<=7. The else Statement
else executes when the if condition is False.
Syntax
if condition:
# if condition is True else:
# if condition is FalseExample:
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")Output:
You cannot vote yet.8. if + else Flow
Consider:
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")The flow is:
age >= 18?
/ \
True False
/ \
Adult MinorOnly one branch executes.
9. The elif Statement
elif means:
else if
It allows us to check another condition when the previous condition was false.
Example:
marks = 75
if marks >= 80:
print("A+")
elif marks >= 70:
print("A")
else:
print("Below A")Output:
A10. Multiple elif Conditions
We can have multiple elif statements.
marks = 65
if marks >= 80:
print("A+")
elif marks >= 70:
print("A")
elif marks >= 60:
print("B+")
elif marks >= 50:
print("B")
else:
print("Fail")Output:
B+Python checks the conditions from top to bottom.
11. Important: Only the First Matching Branch Executes
Consider:
marks = 85
if marks >= 50:
print("Pass")
elif marks >= 80:
print("Excellent")Output:
PassWhy didn't "Excellent" print?
Because the first condition:
marks >= 50is already True.
Python executes that block and skips the remaining elif conditions.
Therefore, when using ranges, put more specific/highest conditions first.
Correct:
if marks >= 80:
print("Excellent")
elif marks >= 50:
print("Pass")
else:
print("Fail")12. Multiple Conditions Using and
The and operator requires both conditions to be True.
Example:
age = 25 has_id = True
if age >= 18 and has_id:
print("Access granted")
else:
print("Access denied")Output:
Access grantedBoth conditions must be satisfied.
13. Multiple Conditions Using or
or requires at least one condition to be True.
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
else:
print("Working day")Output:
Weekend14. Using not
not reverses a Boolean result.
logged_in = False
if not logged_in:
print("Please login first.")Output:
Please login first.15. Combining and, or, and not
Conditions can be combined.
age = 25 has_id = True has_ticket = True
if age >= 18 and has_id and has_ticket:
print("Entry allowed")
else:
print("Entry denied")All three conditions must be true.
16. Conditions with Strings
Conditional statements can compare strings.
username = "admin"
if username == "admin":
print("Administrator")
else:
print("Regular User")17. Case-Sensitive String Comparison
Python string comparisons are case-sensitive.
username = "Admin"
if username == "admin":
print("Correct")
else:
print("Different username")Output:
Different usernameTo make the comparison case-insensitive:
username = "Admin"
if username.lower() == "admin":
print("Correct username")18. Conditions with User Input
A very common pattern is:
name = input("Enter your name: ")
if name == "Raj":
print("Welcome Raj")
else:
print("Welcome Guest")User input is stored in the variable and then evaluated.
19. Numeric User Input
Remember that input() returns a string.
Therefore:
age = input("Enter your age: ")should normally be converted before numeric comparison:
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")
else:
print("Minor")20. Practical Example : Voting Eligibility
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")This is a simple real-world decision-making program.
21. Practical Example : Even or Odd
The modulus operator can be combined with conditions.
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even number")
else:
print("Odd number")If:
number = 12then:
12 % 2 = 0so the number is even.
22. Practical Example : Positive, Negative, or Zero
We can use multiple conditions.
number = int(input("Enter a number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")Possible results:
10 → Positive
-5 → Negative
0 → Zero23. Practical Example : Student Grade
marks = float(input("Enter your marks: "))
if marks >= 80:
print("Grade: A+")
elif marks >= 70:
print("Grade: A")
elif marks >= 60:
print("Grade: B+")
elif marks >= 50:
print("Grade: B")
elif marks >= 40:
print("Grade: C")
else:
print("Grade: Fail")This is a practical example of using multiple elif conditions.
24. Practical Example : Pass or Fail
Suppose a student must score at least 40 in every subject.
python_marks = 65 database_marks = 55 web_marks = 70
if python_marks >= 40 and database_marks >= 40 and web_marks >= 40:
print("Pass")
else:
print("Fail")Here, all three conditions must be true.
25. Nested if
An if statement inside another if statement is called a nested if.
Example:
age = 25 has_id = True
if age >= 18:
if has_id:
print("Entry allowed")The second condition is checked only when the first condition is true.
26. Nested if with else
age = 20 has_id = False
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("You are underage")Output:
ID required27. Nested Conditions in Real Programs
Nested conditions can represent multiple levels of decisions.
For example:
username = input("Username: ")
password = input("Password: ")
if username == "admin":
if password == "python123":
print("Login successful")
else:
print("Incorrect password")
else:
print("Unknown username")28. Avoid Unnecessary Nesting
Sometimes nested conditions can be simplified.
Instead of:
if age >= 18:
if has_id:
print("Allowed")we can write:
if age >= 18 and has_id:
print("Allowed")The second version is often easier to read.
29. if with Membership Operators
The in operator works well with conditions.
courses = ["Python", "Django", "MERN"]
course = input("Enter course: ")
if course in courses:
print("Course available")
else:
print("Course not available")30. if with Dictionaries
Remember that in checks dictionary keys.
student = {
"name": "Raj",
"age": 25,
"course": "Python"
}
if "course" in student:
print("Course information is available")31. Checking Dictionary Values
student = {
"name": "Raj",
"age": 25,
"course": "Python"
}
if "Python" in student.values():
print("Student is learning Python")32. Conditions with Lists
A list can also be used in a condition.
students = ["Raj", "John", "Sita"]
name = input("Enter your name: ")
if name in students:
print("Student found")
else:
print("Student not found")33. Truthy and Falsy Values
Python does not always require an explicit comparison.
For example:
name = "Raj"
if name:
print("Name is available")Because "Raj" is a non-empty string, it is considered truthy.
An empty string is considered falsy:
name = ""
if name:
print("Name is available")
else:
print("Name is empty")Output:
Name is empty34. Common Falsy Values
These values are generally considered false in conditions:
False None 0 0.0 ""
[]
()
{}
set()Example:
items = []
if items:
print("Items are available")
else:
print("No items found")Output:
No items found35. Using bool() to Understand Conditions
You can see how Python evaluates values:
print(bool(0))
print(bool(10))
print(bool(""))
print(bool("Python"))
print(bool([]))
print(bool([1, 2]))Output:
False
True
False
True
False
TrueThis becomes useful when understanding conditions.
36. Conditional Expression : Ternary Operator
Python allows a simple if-else decision to be written in one line.
Example:
age = 20
result = "Adult" if age >= 18 else "Minor"
print(result)Output:
AdultThe structure is:
value_if_true if condition else value_if_false37. Ternary Example
number = 10
result = "Even" if number % 2 == 0 else "Odd"
print(result)Output:
EvenTernary expressions are useful for simple decisions, but regular if-else is often easier to read when the logic becomes complicated.
38. Nested Ternary : Use Carefully
Python technically allows:
marks = 75
grade = "A+" if marks >= 80 else "A" if marks >= 70 else "B"
print(grade)This works, but it can become difficult to read.
For beginners, prefer:
if marks >= 80:
grade = "A+" elif marks >= 70:
grade = "A" else:
grade = "B"Readable code is usually better than clever code.
39. Using pass
Sometimes you want to create a condition but don't want to write its implementation yet.
Python provides:
passExample:
age = 25
if age >= 18:
pass else:
print("Minor")pass does nothing.
It acts as a placeholder.
40. Common Mistake : Using = Instead of ==
Incorrect:
age = 18
if age = 18:
print("Correct")This produces a syntax error.
Correct:
if age == 18:
print("Correct")Remember:
= → assignment
== → comparison41. Common Mistake : Forgetting the Colon
Incorrect:
if age >= 18
print("Adult")Correct:
if age >= 18:
print("Adult")42. Common Mistake : Incorrect Indentation
Incorrect:
if age >= 18:
print("Adult")Correct:
if age >= 18:
print("Adult")43. Common Mistake : Comparing Input Without Conversion
Potential problem:
age = input("Enter age: ")
if age >= 18:
print("Adult")age is a string, so this comparison is invalid.
Correct:
age = int(input("Enter age: "))
if age >= 18:
print("Adult")44. Common Mistake : Wrong Condition Order
Avoid:
marks = 85
if marks >= 40:
print("Pass")
elif marks >= 80:
print("Excellent")The elif will never be reached for marks of 80 or more.
Better:
if marks >= 80:
print("Excellent")
elif marks >= 40:
print("Pass")
else:
print("Fail")45. Practical Example : Login System
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "python123":
print("Login successful")
else:
print("Invalid username or password")This combines:
input()- String comparison
andifelse
46. Practical Example : Discount System
amount = float(input("Enter purchase amount: "))
if amount >= 10000:
discount = 20 elif amount >= 5000:
discount = 10 elif amount >= 2000:
discount = 5 else:
discount = 0
discount_amount = amount * discount / 100 final_amount = amount - discount_amount
print("Discount:", discount, "%")
print("Discount Amount:", discount_amount)
print("Final Amount:", final_amount)This is a good example of a real business rule implemented using conditional statements.
47. Practical Example : Course Eligibility
age = int(input("Enter your age: "))
education = input("Enter your education level: ")
if age >= 18 and education == "Bachelor":
print("Eligible for the advanced program")
elif age >= 18:
print("Eligible for the basic program")
else:
print("Not eligible")48. Practical Example : ATM Withdrawal
balance = 10000
amount = float(input("Enter withdrawal amount: "))
if amount <= 0:
print("Invalid amount")
elif amount > balance:
print("Insufficient balance")
else:
balance = balance - amount
print("Withdrawal successful")
print("Remaining balance:", balance)This demonstrates how multiple conditions can protect a program from invalid input.
49. Practical Example : Temperature
temperature = float(input("Enter temperature: "))
if temperature >= 35:
print("Very Hot")
elif temperature >= 25:
print("Warm")
elif temperature >= 15:
print("Moderate")
else:
print("Cold")50. Copy Code
The following section contains the complete copy-ready code for this lesson.
# ========================================== # Python Conditional Statements # ==========================================
# ------------------------------------------ # 1. Basic if statement # ------------------------------------------
age = 25
if age >= 18:
print("You are an adult.")
# ------------------------------------------ # 2. if with comparison # ------------------------------------------
number = 10
if number == 10:
print("Number is 10")
# ------------------------------------------ # 3. if and else # ------------------------------------------
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
# ------------------------------------------ # 4. if, elif and else # ------------------------------------------
marks = 75
if marks >= 80:
print("A+")
elif marks >= 70:
print("A")
elif marks >= 60:
print("B+")
elif marks >= 50:
print("B")
elif marks >= 40:
print("C")
else:
print("Fail")
# ------------------------------------------ # 5. Multiple conditions using and # ------------------------------------------
age = 25 has_id = True
if age >= 18 and has_id:
print("Access granted")
else:
print("Access denied")
# ------------------------------------------ # 6. Multiple conditions using or # ------------------------------------------
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
else:
print("Working day")
# ------------------------------------------ # 7. Using not # ------------------------------------------
logged_in = False
if not logged_in:
print("Please login first.")
# ------------------------------------------ # 8. String comparison # ------------------------------------------
username = "admin"
if username == "admin":
print("Administrator")
else:
print("Regular User")
# ------------------------------------------ # 9. Case-insensitive comparison # ------------------------------------------
username = "Admin"
if username.lower() == "admin":
print("Correct username")
else:
print("Incorrect username")
# ------------------------------------------ # 10. User input # ------------------------------------------
name = input("Enter your name: ")
if name == "Raj":
print("Welcome Raj")
else:
print("Welcome Guest")
# ------------------------------------------ # 11. Numeric user input # ------------------------------------------
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")
else:
print("Minor")
# ------------------------------------------ # 12. Even or odd # ------------------------------------------
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
# ------------------------------------------ # 13. Positive, negative or zero # ------------------------------------------
number = int(input("Enter another number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
# ------------------------------------------ # 14. Nested if # ------------------------------------------
age = 25 has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
# ------------------------------------------ # 15. Nested if with else # ------------------------------------------
age = 20 has_id = False
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("You are underage")
# ------------------------------------------ # 16. Membership operator # ------------------------------------------
courses = ["Python", "Django", "MERN"]
course = "Python"
if course in courses:
print("Course available")
else:
print("Course not available")
# ------------------------------------------ # 17. Dictionary condition # ------------------------------------------
student = {
"name": "Raj",
"age": 25,
"course": "Python"
}
if "course" in student:
print("Course information is available")
if "Python" in student.values():
print("Student is learning Python")
# ------------------------------------------ # 18. Truthy and falsy values # ------------------------------------------
name = ""
if name:
print("Name is available")
else:
print("Name is empty")
# ------------------------------------------ # 19. Ternary / conditional expression # ------------------------------------------
age = 20
result = "Adult" if age >= 18 else "Minor"
print(result)
# ------------------------------------------ # 20. Ternary even/odd # ------------------------------------------
number = 10
result = "Even" if number % 2 == 0 else "Odd"
print(result)
# ------------------------------------------ # 21. pass statement # ------------------------------------------
age = 25
if age >= 18:
pass else:
print("Minor")
# ------------------------------------------ # 22. Login system # ------------------------------------------
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "python123":
print("Login successful")
else:
print("Invalid username or password")
# ------------------------------------------ # 23. Discount system # ------------------------------------------
amount = float(input("Enter purchase amount: "))
if amount >= 10000:
discount = 20 elif amount >= 5000:
discount = 10 elif amount >= 2000:
discount = 5 else:
discount = 0
discount_amount = amount * discount / 100 final_amount = amount - discount_amount
print("Discount:", discount, "%")
print("Discount Amount:", discount_amount)
print("Final Amount:", final_amount)
# ------------------------------------------ # 24. ATM withdrawal # ------------------------------------------
balance = 10000
amount = float(input("Enter withdrawal amount: "))
if amount <= 0:
print("Invalid amount")
elif amount > balance:
print("Insufficient balance")
else:
balance = balance - amount
print("Withdrawal successful")
print("Remaining balance:", balance)51. Practice Exercise 1 : Age Category
Ask the user for their age.
Display:
0–12 → Child
13–19 → Teenager
20–59 → Adult
60+ → Senior CitizenUse if, elif, and else.
52. Practice Exercise 2 : Number Checker
Ask the user for a number.
Determine whether it is:
- Positive
- Negative
- Zero
Then additionally determine whether a positive number is:
- Even
- Odd
53. Practice Exercise 3 : Login System
Create a login program with:
correct_username = "admin" correct_password = "python123"Ask the user for username and password.
Display:
Login successfulor:
Invalid username or password54. Practice Exercise 4 : Grade Calculator
Ask for marks and display:
90–100 → A+
80–89 → A
70–79 → B+
60–69 → B
50–59 → C+
40–49 → C
Below 40 → FailAlso make sure marks are within a valid range of 0–100.
55. Practice Exercise 5 : Simple Calculator
Ask the user for:
First number
Second number
OperatorFor example:
Enter first number: 20
Enter second number: 5
Enter operator: *Display:
Result: 100Support:
+
-
*
/
%This is an excellent exercise for combining:
input()- Type conversion
ifelif- Arithmetic operators
56. Practice Exercise 6 : Shopping Discount
Create a discount system:
Purchase >= 10000 → 20% discount
Purchase >= 5000 → 10% discount
Purchase >= 2000 → 5% discount
Below 2000 → No discountCalculate the final amount.
57. Challenge : ATM System
Create a simple ATM program.
Starting balance:
balance = 50000Ask the user for withdrawal amount.
Rules:
Amount <= 0 → Invalid amount
Amount > balance → Insufficient balance
Otherwise → Withdrawal successfulDisplay the remaining balance after a successful withdrawal.
58. Challenge : Course Admission System
Create a program for SkillMantra course admission.
Ask for:
Age
Education
Programming experienceExample rules:
Age >= 18 AND education == "Bachelor"
→ Eligible for Advanced Program
Age >= 18
→ Eligible for Beginner Program
Age < 18
→ Not eligibleExtend the program with your own rules.