Module 9: Conditional Statements in Python
Conditional statements are one of the most important concepts in Python programming. They allow a program to make decisions based on conditions.
A program can check whether something is true or false and then execute the appropriate block of code.
For example:
- If a student's marks are 90 or higher, assign grade A.
- If a user enters the correct password, allow login.
- If an account balance is sufficient, allow a withdrawal.
- If the temperature is high, display a warning.
- If a number is even, display an appropriate message.
In simple terms:
1Condition → True → Execute one block 2Condition → False → Execute another block
By the end of this module, you will understand how to use if, else, elif, nested conditions, logical operators, match...case, and Python's conditional expression.
What Are Conditional Statements?
A conditional statement evaluates an expression and decides which code should run.
For example:
1age = 20 2 3if age >= 18: 4 print("You are an adult.")
Here, Python evaluates:
1age >= 18
The result is:
1True
Therefore, Python executes the print() statement.
If the condition evaluates to False, the code inside the if block is skipped.
Python commonly uses these conditional structures:
| Statement | Purpose |
|---|---|
if | Executes code when a condition is true |
if...else | Chooses between two alternatives |
if...elif...else | Checks multiple conditions |
Nested if | Places a condition inside another condition |
match...case | Matches a value against multiple patterns |
| Conditional expression | Writes a simple condition in one line |
Boolean Values in Python
Conditions produce Boolean values.
Python has two Boolean values:
1True 2False
For example:
1age = 20 2 3print(age >= 18) 4print(age < 18)
Output:
1True 2False
The expression:
1age >= 18
is True because 20 is greater than or equal to 18.
Comparison Operators
Comparison operators are frequently used with conditional statements.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
Example:
1temperature = 35 2 3print(temperature > 30) 4print(temperature == 35) 5print(temperature < 20)
Output:
1True 2True 3False
Indentation in Python
Python uses indentation to define blocks of code.
The statements belonging to an if, else, or elif block must be indented.
Correct:
1age = 20 2 3if age >= 18: 4 print("Adult")
Incorrect:
1age = 20 2 3if age >= 18: 4print("Adult")
The incorrect version produces an error similar to:
1IndentationError: expected an indented block
A common Python convention is to use four spaces for indentation.
You can also use nested indentation:
1age = 20 2 3if age >= 18: 4 print("Adult") 5 6 if age >= 60: 7 print("Senior adult")
The if Statement
The if statement executes a block of code only when its condition is True.
Syntax
1if condition: 2 statement
The colon : is required after the condition.
Example
1age = 21 2 3if age >= 18: 4 print("You are eligible to vote.")
Output:
1You are eligible to vote.
If age were 16, the condition would be false and nothing would be printed.
Practical if Examples
Check a Temperature
1temperature = 38 2 3if temperature > 35: 4 print("Warning: It is very hot today.")
Output:
1Warning: It is very hot today.
Check Passing Marks
1marks = 72 2 3if marks >= 40: 4 print("You passed the exam.")
Output:
1You passed the exam.
Check Account Balance
1balance = 5000 2minimum_balance = 1000 3 4if balance >= minimum_balance: 5 print("Account balance is sufficient.")
The if...else Statement
The if...else statement allows a program to choose between two possibilities.
If the condition is True, the if block runs.
If the condition is False, the else block runs.
Syntax
1if condition: 2 # code when condition is True 3else: 4 # code when condition is False
Example
1age = 16 2 3if age >= 18: 4 print("Eligible to vote.") 5else: 6 print("Not eligible to vote.")
Output:
1Not eligible to vote.
Check Whether a Number Is Even or Odd
The modulo operator % returns the remainder of a division.
A number is even when its remainder after division by 2 is 0.
1number = int(input("Enter a number: ")) 2 3if number % 2 == 0: 4 print("Even number") 5else: 6 print("Odd number")
Example:
1Enter a number: 17 2Odd number
Check Whether a Number Is Positive, Negative, or Zero
A simple if...else is not enough when three possibilities exist.
For that situation, use if...elif...else.
1number = float(input("Enter a number: ")) 2 3if number > 0: 4 print("Positive") 5elif number < 0: 6 print("Negative") 7else: 8 print("Zero")
The elif Statement
The elif statement means "else if".
It allows Python to test multiple conditions.
Syntax
1if condition1: 2 statement 3elif condition2: 4 statement 5elif condition3: 6 statement 7else: 8 statement
Python checks conditions from top to bottom.
As soon as it finds a condition that is True, its block executes and the remaining conditions are skipped.
Grade Calculator
1marks = 86 2 3if marks >= 90: 4 grade = "A" 5elif marks >= 80: 6 grade = "B" 7elif marks >= 70: 8 grade = "C" 9elif marks >= 60: 10 grade = "D" 11else: 12 grade = "F" 13 14print("Grade:", grade)
Output:
1Grade: B
Notice that the conditions are checked from the highest range to the lowest.
This ordering is important.
For example, this would be incorrect:
1if marks >= 60: 2 grade = "D" 3elif marks >= 90: 4 grade = "A"
For 95, Python would stop at marks >= 60 and assign grade D.
Traffic Signal Example
1signal = input("Enter signal color: ").strip().lower() 2 3if signal == "red": 4 print("Stop") 5elif signal == "yellow": 6 print("Get ready") 7elif signal == "green": 8 print("Go") 9else: 10 print("Invalid signal")
Using .strip().lower() makes the input more reliable.
For example:
1GREEN
becomes:
1green
Month Finder
For a small number of fixed choices, elif can be used:
1month = int(input("Enter month number: ")) 2 3if month == 1: 4 print("January") 5elif month == 2: 6 print("February") 7elif month == 3: 8 print("March") 9elif month == 4: 10 print("April") 11elif month == 5: 12 print("May") 13elif month == 6: 14 print("June") 15elif month == 7: 16 print("July") 17elif month == 8: 18 print("August") 19elif month == 9: 20 print("September") 21elif month == 10: 22 print("October") 23elif month == 11: 24 print("November") 25elif month == 12: 26 print("December") 27else: 28 print("Invalid month")
For many fixed values like this, Python's match...case can also make the code easier to organize.
Nested if Statements
A nested if statement is an if statement inside another conditional block.
Syntax
1if condition1: 2 if condition2: 3 statement
Example
1age = 25 2citizen = True 3 4if age >= 18: 5 if citizen: 6 print("Eligible to vote.")
Output:
1Eligible to vote.
The inner condition is checked only when the outer condition is true.
Scholarship Eligibility
1marks = 92 2attendance = 88 3 4if marks >= 90: 5 if attendance >= 75: 6 print("Scholarship approved.") 7 else: 8 print("Attendance is too low.") 9else: 10 print("Marks are too low.")
Output:
1Scholarship approved.
However, when the conditions are independent, logical operators can often make the code simpler:
1if marks >= 90 and attendance >= 75: 2 print("Scholarship approved.") 3else: 4 print("Scholarship requirements not met.")
This is often easier to read.
ATM Example
A nested condition can represent multiple decision levels:
1correct_pin = 1234 2balance = 5000 3 4entered_pin = int(input("Enter PIN: ")) 5 6if entered_pin == correct_pin: 7 amount = float(input("Enter withdrawal amount: ")) 8 9 if amount <= 0: 10 print("Enter a valid amount.") 11 elif amount <= balance: 12 balance -= amount 13 print("Transaction successful.") 14 print("Remaining balance:", balance) 15 else: 16 print("Insufficient balance.") 17else: 18 print("Invalid PIN.")
This example demonstrates several useful concepts:
- Nested conditions
- User input
- Comparison operators
elif- Validation
- Updating a variable
Logical Operators
Logical operators allow you to combine multiple conditions.
Python provides three main logical operators:
1and 2or 3not
The and Operator
and returns True only when both conditions are true.
1age = 22 2citizen = True 3 4if age >= 18 and citizen: 5 print("Eligible to vote.")
Both conditions must be satisfied.
A useful example is checking whether a student meets both requirements:
1marks = 85 2attendance = 80 3 4if marks >= 75 and attendance >= 75: 5 print("Eligible for the scholarship.") 6else: 7 print("Not eligible.")
The or Operator
or returns True when at least one condition is true.
1day = "Sunday" 2 3if day == "Saturday" or day == "Sunday": 4 print("Weekend") 5else: 6 print("Working day")
Output:
1Weekend
The not Operator
The not operator reverses a Boolean value.
1logged_in = False 2 3if not logged_in: 4 print("Please log in.")
Output:
1Please log in.
Another example:
1is_blocked = False 2 3if not is_blocked: 4 print("User can continue.")
Combining Multiple Conditions
You can combine multiple logical operators:
1age = 25 2has_id = True 3is_blocked = False 4 5if age >= 18 and has_id and not is_blocked: 6 print("Access granted.") 7else: 8 print("Access denied.")
Parentheses can improve readability when conditions become more complex:
1if (age >= 18 and has_id) and not is_blocked: 2 print("Access granted.")
Truthy and Falsy Values
Python conditions do not always need to contain a comparison.
Many values can be evaluated directly as True or False.
Common falsy values include:
1False 2None 30 40.0 5"" 6[] 7{} 8set()
For example:
1username = "" 2 3if username: 4 print("Username entered.") 5else: 6 print("Username is empty.")
Output:
1Username is empty.
This is commonly used when checking whether a string, list, dictionary, or other collection contains data.
Conditional Expressions
Python provides a concise way to write simple if...else logic.
This is called a conditional expression and is sometimes referred to as the ternary operator.
Syntax
1value_if_true if condition else value_if_false
Example
1age = 20 2 3message = "Adult" if age >= 18 else "Minor" 4 5print(message)
Output:
1Adult
Even or Odd Using a Conditional Expression
1number = 8 2 3result = "Even" if number % 2 == 0 else "Odd" 4 5print(result)
Output:
1Even
Conditional expressions are best used for short and simple decisions.
Avoid using complicated nested expressions because they can make code difficult to read.
Finding the Larger Number
1a = 25 2b = 40 3 4largest = a if a > b else b 5 6print("Largest:", largest)
Output:
1Largest: 40
For three or more values, a normal if...elif...else structure or built-in functions such as max() may be clearer.
match...case in Python
Python introduced match...case in Python 3.10.
It provides structural pattern matching and can be useful when you need to compare a value against multiple patterns.
For simple value matching, it can look similar to a switch statement found in other languages.
Basic Syntax
1match value: 2 case pattern1: 3 statement 4 case pattern2: 5 statement 6 case _: 7 statement
The _ pattern works as a default case.
Day Example
1day = 2 2 3match day: 4 case 1: 5 print("Monday") 6 case 2: 7 print("Tuesday") 8 case 3: 9 print("Wednesday") 10 case 4: 11 print("Thursday") 12 case 5: 13 print("Friday") 14 case 6: 15 print("Saturday") 16 case 7: 17 print("Sunday") 18 case _: 19 print("Invalid day")
Output:
1Tuesday
Calculator Using match...case
1first = float(input("Enter first number: ")) 2second = float(input("Enter second number: ")) 3operator = input("Enter operator (+, -, *, /): ").strip() 4 5match operator: 6 case "+": 7 result = first + second 8 case "-": 9 result = first - second 10 case "*": 11 result = first * second 12 case "/": 13 if second == 0: 14 print("Cannot divide by zero.") 15 else: 16 result = first / second 17 print("Result:", result) 18 case _: 19 print("Invalid operator.")
For the first three operations, you could simplify the final output:
1match operator: 2 case "+": 3 print(first + second) 4 case "-": 5 print(first - second) 6 case "*": 7 print(first * second) 8 case "/": 9 if second == 0: 10 print("Cannot divide by zero.") 11 else: 12 print(first / second) 13 case _: 14 print("Invalid operator.")
Menu System with match...case
1choice = input("Choose an option: ").strip() 2 3match choice: 4 case "1": 5 print("Opening Home...") 6 case "2": 7 print("Opening Profile...") 8 case "3": 9 print("Opening Settings...") 10 case "4": 11 print("Logging out...") 12 case _: 13 print("Invalid choice.")
Notice that input() returns a string, so the cases are strings:
1case "1":
rather than integers:
1case 1:
When Should You Use if or match?
Use if...elif...else when conditions involve comparisons or ranges:
1if marks >= 90: 2 grade = "A" 3elif marks >= 80: 4 grade = "B"
Use match...case when you are matching a value against several patterns:
1match command: 2 case "start": 3 print("Starting...") 4 case "stop": 5 print("Stopping...")
Choosing the structure that best represents the decision makes code easier to understand and maintain.
Practice Project: Grade Calculator
Let's create a complete grade calculator with input validation.
Grading System
| Marks | Grade |
|---|---|
| 90–100 | A |
| 80–89 | B |
| 70–79 | C |
| 60–69 | D |
| 0–59 | F |
Code
1marks = float(input("Enter your marks: ")) 2 3if not 0 <= marks <= 100: 4 print("Invalid marks. Enter a value from 0 to 100.") 5elif marks >= 90: 6 print("Grade: A") 7elif marks >= 80: 8 print("Grade: B") 9elif marks >= 70: 10 print("Grade: C") 11elif marks >= 60: 12 print("Grade: D") 13else: 14 print("Grade: F")
Example:
1Enter your marks: 86 2Grade: B
The validation condition:
1if not 0 <= marks <= 100:
uses Python's chained comparison syntax.
This:
10 <= marks <= 100
means:
10 <= marks and marks <= 100
Practice Project: Login System
A basic login example can demonstrate multiple conditions.
1correct_username = "admin" 2correct_password = "python123" 3 4username = input("Username: ") 5password = input("Password: ") 6 7if username == correct_username and password == correct_password: 8 print("Login successful.") 9else: 10 print("Invalid username or password.")
Example:
1Username: admin 2Password: python123 3Login successful.
In a real application, passwords should never be stored as plain text. Passwords should be securely hashed and authenticated using an appropriate authentication system.
Login System with Three Attempts
Loops can be combined with conditional statements to create a limited login attempt system.
1correct_username = "admin" 2correct_password = "python123" 3 4for attempt in range(1, 4): 5 username = input("Username: ") 6 password = input("Password: ") 7 8 if username == correct_username and password == correct_password: 9 print("Login successful.") 10 break 11 12 remaining = 3 - attempt 13 14 if remaining > 0: 15 print(f"Invalid credentials. Attempts remaining: {remaining}") 16else: 17 print("Too many failed attempts.")
This example combines:
forloopsifelsebreak- Logical operators
- Formatted strings
Practice Project: Electricity Bill Calculator
Conditional statements are useful for implementing pricing rules.
Suppose the electricity rate is:
- First 100 units: ₹5 per unit
- Next 100 units: ₹7 per unit
- Above 200 units: ₹10 per unit
1units = float(input("Enter electricity units: ")) 2 3if units < 0: 4 print("Invalid units.") 5elif units <= 100: 6 bill = units * 5 7 print(f"Electricity bill: ₹{bill:.2f}") 8elif units <= 200: 9 bill = (100 * 5) + ((units - 100) * 7) 10 print(f"Electricity bill: ₹{bill:.2f}") 11else: 12 bill = (100 * 5) + (100 * 7) + ((units - 200) * 10) 13 print(f"Electricity bill: ₹{bill:.2f}")
This is a good example of using conditions to implement different pricing ranges.
Practice Project: Simple Calculator
1first = float(input("Enter first number: ")) 2second = float(input("Enter second number: ")) 3operator = input("Enter operator (+, -, *, /): ").strip() 4 5if operator == "+": 6 result = first + second 7elif operator == "-": 8 result = first - second 9elif operator == "*": 10 result = first * second 11elif operator == "/": 12 if second == 0: 13 print("Error: Cannot divide by zero.") 14 else: 15 result = first / second 16 print("Result:", result) 17else: 18 print("Error: Invalid operator.") 19 20if operator in {"+", "-", "*"}: 21 print("Result:", result)
A simpler version is often preferable for beginners:
1if operator == "+": 2 print(first + second) 3elif operator == "-": 4 print(first - second) 5elif operator == "*": 6 print(first * second) 7elif operator == "/": 8 if second != 0: 9 print(first / second) 10 else: 11 print("Cannot divide by zero.") 12else: 13 print("Invalid operator.")
The second version avoids creating a variable that is not always assigned.
Practice Exercises
Exercise 1: Find the Largest of Three Numbers
Write a program that accepts three numbers and prints the largest.
Example:
1Enter first number: 25 2Enter second number: 40 3Enter third number: 18 4 5Largest: 40
One solution is:
1a = float(input("Enter first number: ")) 2b = float(input("Enter second number: ")) 3c = float(input("Enter third number: ")) 4 5if a >= b and a >= c: 6 largest = a 7elif b >= c: 8 largest = b 9else: 10 largest = c 11 12print("Largest:", largest)
Exercise 2: Leap Year Checker
A year is a leap year when:
- It is divisible by 400, or
- It is divisible by 4 but not by 100.
1year = int(input("Enter year: ")) 2 3if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): 4 print("Leap year") 5else: 6 print("Not a leap year")
Exercise 3: Age Category
Create a program that categorizes a person's age.
1age = int(input("Enter age: ")) 2 3if age < 0: 4 print("Invalid age") 5elif age < 13: 6 print("Child") 7elif age < 20: 8 print("Teenager") 9elif age < 60: 10 print("Adult") 11else: 12 print("Senior citizen")
Exercise 4: Password Validation
Create a program that checks whether a password contains at least eight characters.
1password = input("Enter password: ") 2 3if len(password) >= 8: 4 print("Password length is valid.") 5else: 6 print("Password must contain at least 8 characters.")
Remember that checking only password length is not a complete password-strength check.
Exercise 5: Check Voting Eligibility
Write a program that checks whether a person is eligible to vote.
1age = int(input("Enter age: ")) 2 3if age >= 18: 4 print("Eligible to vote.") 5else: 6 print("Not eligible to vote.")
Exercise 6: Temperature Classification
Create a program that categorizes temperature:
1Below 10 → Cold 210–24 → Cool 325–34 → Warm 435 and above → Hot
Exercise 7: Divisibility Checker
Write a program that checks whether a number is divisible by both 3 and 5.
Example:
1number = int(input("Enter a number: ")) 2 3if number % 3 == 0 and number % 5 == 0: 4 print("Divisible by both 3 and 5.") 5else: 6 print("Not divisible by both 3 and 5.")
Common Mistakes in Conditional Statements
Using = Instead of ==
= is the assignment operator.
== is the equality comparison operator.
Incorrect:
1age = 18 2 3if age = 18: 4 print("Adult")
This produces a syntax error.
Correct:
1if age == 18: 2 print("Adult")
Forgetting the Colon
Incorrect:
1if age >= 18 2 print("Adult")
Correct:
1if age >= 18: 2 print("Adult")
The colon tells Python that a new code block begins.
Incorrect Indentation
Incorrect:
1if age >= 18: 2print("Adult")
Correct:
1if age >= 18: 2 print("Adult")
Using Separate if Statements When elif Is Required
Consider:
1marks = 95 2 3if marks >= 90: 4 print("A") 5 6if marks >= 80: 7 print("B")
Output:
1A 2B
Both conditions are checked independently.
If only one grade should be selected, use elif:
1if marks >= 90: 2 print("A") 3elif marks >= 80: 4 print("B")
Output:
1A
Incorrect Condition Order
Avoid:
1if marks >= 60: 2 print("D") 3elif marks >= 90: 4 print("A")
For 95, the first condition is already true.
Instead, check the highest threshold first:
1if marks >= 90: 2 print("A") 3elif marks >= 60: 4 print("D")
Comparing Input With the Wrong Type
input() always returns a string.
For example:
1age = input("Enter age: ")
Here, age is a string.
For numerical comparisons, convert it:
1age = int(input("Enter age: ")) 2 3if age >= 18: 4 print("Adult")
if vs elif vs else
| Structure | When to use |
|---|---|
if | You need to execute code only when a condition is true |
if...else | You have two possible outcomes |
if...elif...else | You have multiple possible outcomes |
Nested if | One decision depends on another |
match...case | You want to match values or patterns |
| Conditional expression | You need a short one-line decision |
Conditional Statements and Program Flow
Consider this program:
1age = 22 2 3if age >= 18: 4 print("Adult") 5else: 6 print("Minor") 7 8print("Program finished.")
Python executes statements from top to bottom.
The condition determines which branch runs:
1Start 2 ↓ 3Check age >= 18 4 ↓ 5True ──→ Print "Adult" 6 │ 7 └────→ Print "Program finished."
Understanding this flow is essential before learning more advanced topics such as loops, functions, exception handling, and object-oriented programming.
Key Takeaways
- Conditional statements allow Python programs to make decisions.
ifexecutes code when a condition is true.elseprovides an alternative when the condition is false.elifallows multiple conditions to be checked.- Python uses indentation to define conditional blocks.
- Comparison operators include
==,!=,>,<,>=, and<=. - Logical operators include
and,or, andnot. - Conditions can use Boolean, numeric, string, and collection values.
- Nested
ifstatements allow one condition to depend on another. - Conditional expressions are useful for simple one-line decisions.
match...caseis available from Python 3.10 and supports structural pattern matching.- Always validate user input when building interactive programs.
- Use the simplest conditional structure that clearly expresses the decision.
After mastering conditional statements, you will be ready to combine them with loops, functions, lists, dictionaries, and other Python concepts to build more useful programs.