Working with if-else Statements in Python
Course: Python Programming
Topic: Working with if-else Statements
Course Link: Python Training Course – JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to if-else Statements
In Python, decision-making is an essential programming concept that allows a program to choose which statements to execute based on a condition. The if, elif, and else statements are used to control the flow of a program.
For example, a program can determine whether a student has passed an examination, whether a customer qualifies for a discount, whether a person is eligible to vote, or whether a number is positive or negative.
Without conditional statements, a program would generally execute instructions in sequence without choosing different actions based on changing conditions.
age = 20
if age >= 18:
print("You are eligible to vote")
else:
print("You are not eligible to vote")
Output:
You are eligible to vote
In this example, Python evaluates the condition age >= 18. Because the condition is true, the first block executes and the else block is skipped.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand the purpose of conditional statements in Python.
- Explain how the
if statement works.
- Write programs using
if-else statements.
- Use
elif to evaluate multiple conditions.
- Implement nested
if statements.
- Combine conditions with logical operators.
- Understand truth values and Boolean expressions.
- Apply conditional statements to real-world problems.
- Identify common syntax and indentation errors.
- Practice decision-making using small Python programs.
3. What Is an if Statement?
An if statement executes a block of code only when its condition evaluates to a truthy value. If the condition is false, the block is skipped.
The if statement is useful when a program needs to perform an action only if a specific requirement is satisfied.
Syntax
if condition:
statement
Explanation:
if is the Python keyword that starts the conditional statement.
condition is an expression that Python evaluates.
- The colon (
:) marks the beginning of the conditional block.
- The indented statement executes when the condition is truthy.
Example: Checking a Passing Score
marks = 75
if marks >= 40:
print("Congratulations! You passed.")
Output:
Congratulations! You passed.
If marks were less than 40, the message would not be displayed because there is no else block.
4. Understanding the if-else Statement
An if-else statement allows a program to select between two alternative blocks of code. The if block executes when the condition is truthy, while the else block executes when the condition is falsy.
Syntax
if condition:
# Executes when the condition is true
statement1
else:
# Executes when the condition is false
statement2
Only one of these two branches is selected during a normal execution of the same if-else statement.
Example: Checking Whether a Number Is Even or Odd
number = 7
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
Output:
The number is odd
The modulus operator (%) returns the remainder after division. An even integer has a remainder of zero when divided by two, while an odd integer does not.
5. How an if-else Statement Works
Python evaluates the condition before deciding which branch to execute. The execution process can be understood in the following steps:
- The program reaches the
if statement.
- Python evaluates the condition.
- If the condition is truthy, the indented
if block executes.
- If the condition is falsy, Python skips the
if block and executes the else block, if one exists.
- After the selected block finishes, execution continues with the next statement outside the conditional structure.
Example
temperature = 32
if temperature > 30:
print("It is a hot day")
else:
print("The weather is cool")
print("Weather check completed")
Output:
It is a hot day
Weather check completed
The final message is outside the conditional structure, so it executes regardless of which branch is selected.
6. Using if-elif-else Statements
Sometimes a program must choose between more than two possible outcomes. Python provides the elif keyword, which means “else if,” to check additional conditions.
An if-elif-else structure evaluates conditions from top to bottom. The first truthy condition determines which block executes. If no condition is truthy, the optional else block executes.
Syntax
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
default_statement
You can use multiple elif branches, but an else branch is optional and can appear only once at the end of the chain.
Example: Student Grade Calculation
marks = 85
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")
Output:
Grade A
Python checks the first condition, then proceeds to the next condition if necessary. Since 85 is less than 90 but greater than or equal to 80, the second branch executes.
7. Difference Between if, if-else, and if-elif-else
| Statement |
Purpose |
Example Use Case |
if |
Executes a block when a condition is truthy. |
Display a warning if stock is low. |
if-else |
Selects one of two alternative blocks. |
Determine whether a number is even or odd. |
if-elif-else |
Selects among multiple alternatives. |
Assign grades based on marks. |
Nested if |
Checks another condition inside a conditional block. |
Check eligibility and then verify documents. |
8. Understanding Boolean Conditions
A Boolean expression evaluates to True or False. Comparison operators such as ==, !=, >, <, >=, and <= are commonly used in conditions.
age = 21
print(age >= 18)
print(age < 18)
Output:
True
False
Python also allows non-Boolean values in conditions. These values are evaluated according to their truthiness.
username = "student"
if username:
print("Username is provided")
else:
print("Username is empty")
Output:
Username is provided
Common falsy values include False, None, numeric zero, and empty collections or strings such as "", [], and {}. Most other values are truthy.
9. Combining Conditions with Logical Operators
Logical operators let you combine multiple conditions into a single decision-making expression.
| Operator |
Meaning |
Example |
and |
Both conditions must be truthy. |
age >= 18 and has_id |
or |
At least one condition must be truthy. |
is_student or has_discount_card |
not |
Reverses the truth value of a condition. |
not is_blocked |
Example: Eligibility for Registration
age = 22
has_id = True
if age >= 18 and has_id:
print("Registration allowed")
else:
print("Registration not allowed")
Output:
Registration allowed
Both conditions must be satisfied for the first branch to execute.
Example: Discount Eligibility
purchase_amount = 1500
is_member = True
if purchase_amount >= 2000 or is_member:
print("Discount available")
else:
print("No discount available")
Output:
Discount available
In this example, membership alone makes the condition truthy, even though the purchase amount is below 2000.
10. Nested if Statements
A nested if statement is an if statement placed inside another conditional block. It is useful when a decision depends on a sequence of related checks.
Syntax
if outer_condition:
if inner_condition:
statement1
else:
statement2
else:
statement3
Example: Login Validation
username = "admin"
password = "python123"
if username == "admin":
if password == "python123":
print("Login successful")
else:
print("Incorrect password")
else:
print("Unknown username")
Output:
Login successful
The inner condition is checked only when the outer username condition is true. In real applications, passwords should be securely stored and verified using appropriate authentication mechanisms rather than hardcoded in source code.
11. Using if-else with Comparison Operators
Comparison operators are frequently used with conditional statements to determine whether a value satisfies a requirement.
Example: Positive, Negative, or Zero
number = -5
if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
else:
print("Zero")
Output:
Negative number
Example: Checking Age
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")
Output:
Minor
12. Checking Even and Odd Numbers
The modulus operator can be combined with an if-else statement to determine whether an integer is even or odd.
number = 14
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
Even number
If the remainder after dividing an integer by 2 is zero, the integer is even. Otherwise, it is odd.
13. Conditional Statements with User Input
The input() function accepts data from the user and returns it as a string. Convert the input to the appropriate type when numerical comparisons are required.
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")
Example input:
Enter your age: 20
Output:
You are eligible to vote
If the user enters text that cannot be converted to an integer, int() raises a ValueError. A robust program should handle invalid input where necessary.
14. Nested Conditions for Multiple Requirements
Nested conditions are helpful when one requirement must be met before another requirement is checked.
Example: Scholarship Eligibility
marks = 92
family_income = 250000
if marks >= 85:
if family_income <= 300000:
print("Eligible for scholarship")
else:
print("Income exceeds the limit")
else:
print("Minimum marks requirement not met")
Output:
Eligible for scholarship
The program first checks the marks requirement. Only if that requirement is satisfied does it evaluate the family income condition.
15. Using Conditional Expressions
For simple decisions, Python supports a conditional expression that selects one of two values. It is sometimes called a ternary expression.
Syntax
value_if_true if condition else value_if_false
Example
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Output:
Adult
Conditional expressions are useful for short assignments. For complex logic, a regular if-else statement is generally easier to read.
16. Using pass in Conditional Statements
The pass statement does nothing when executed. It can be used as a placeholder when Python requires a statement but the implementation has not yet been written.
score = 75
if score >= 50:
pass
else:
print("Score is below 50")
Output: No output.
Because the condition is true, Python executes the pass statement. It then continues with the next statement after the conditional structure.
In finished programs, replace unnecessary placeholders with the intended implementation.
17. Common Mistakes in if-else Statements
| Mistake |
Why It Is a Problem |
Correct Approach |
| Missing colon |
Python raises a syntax error. |
Write if condition:. |
| Incorrect indentation |
Python may raise an indentation error or execute a block incorrectly. |
Use consistent indentation, commonly four spaces. |
Using = instead of == |
Assignment is not an equality comparison. |
Use == when comparing values. |
| Incorrect condition order |
An earlier condition may capture values intended for a later branch. |
Order overlapping conditions carefully. |
Using multiple independent if statements unnecessarily |
More than one block may execute when only one outcome is intended. |
Use if-elif-else for mutually exclusive alternatives. |
| Comparing strings and numbers directly |
Unsupported ordering comparisons can raise TypeError. |
Convert input to the intended type. |
| Forgetting the default case |
Unexpected values may not receive an appropriate response. |
Add an else branch when a default action is needed. |
| Overusing nested conditions |
Deep indentation can make code harder to understand. |
Consider combining conditions or using early returns in functions. |
18. Practical Real-World Examples
Example 1: ATM Withdrawal
balance = 5000
withdrawal = 2000
if withdrawal > 0 and withdrawal <= balance:
balance = balance - withdrawal
print("Withdrawal successful")
print("Remaining balance:", balance)
else:
print("Invalid withdrawal amount")
Output:
Withdrawal successful
Remaining balance: 3000
Example 2: Shopping Discount
purchase_amount = 2500
if purchase_amount >= 2000:
discount = purchase_amount * 0.10
final_amount = purchase_amount - discount
print("Discount:", discount)
print("Final amount:", final_amount)
else:
print("No discount available")
print("Final amount:", purchase_amount)
Output:
Discount: 250.0
Final amount: 2250.0
Example 3: Employee Bonus
performance_score = 90
years_of_service = 5
if performance_score >= 85 and years_of_service >= 3:
print("Eligible for performance bonus")
else:
print("Not eligible for performance bonus")
Output:
Eligible for performance bonus
Example 4: Simple Calculator
num1 = 20
num2 = 10
operator = "/"
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
if num2 != 0:
print(num1 / num2)
else:
print("Cannot divide by zero")
else:
print("Invalid operator")
Output:
2.0
Example 5: Login Status
is_logged_in = True
if is_logged_in:
print("Welcome to your dashboard")
else:
print("Please log in to continue")
Output:
Welcome to your dashboard
19. Best Practices for Writing Conditional Statements
- Use meaningful variable names that clearly communicate what a condition checks.
- Keep conditions simple and readable.
- Use four spaces for each indentation level and remain consistent.
- Use
elif when checking alternative conditions in the same decision chain.
- Use
and and or when several requirements must be evaluated together.
- Order conditions carefully when their ranges overlap.
- Use an
else branch when a default outcome is needed.
- Avoid excessive nesting when a simpler condition can express the same rule.
- Test boundary values, such as exactly 18 years of age or exactly 40 marks.
- Validate user input before performing operations that require a particular data type.
- Use comments when a business rule is not obvious from the code.
- Test both true and false outcomes for each important condition.
20. Practice Exercises
Complete these exercises to improve your understanding of Python decision-making.
- Write a program to determine whether a number is positive or negative.
- Write a program to check whether a number is even or odd.
- Write a program that checks whether a student has passed with at least 40 marks.
- Write a program to classify a person's age as child, teenager, or adult.
- Write a program to find the largest of two numbers.
- Write a program to find the largest of three numbers using
if-elif-else.
- Write a program that checks whether a customer qualifies for a discount.
- Write a program that determines whether a number is within the range 1 to 100, inclusive.
- Write a program that checks whether a user has entered the correct username.
- Write a simple calculator using conditional statements.
- Write a program that checks eligibility based on age and identity verification.
- Write a program that assigns grades based on examination marks.
21. Practice Exercise Solutions
Solution 1: Positive or Negative
number = -8
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
Solution 2: Even or Odd
number = 12
if number % 2 == 0:
print("Even")
else:
print("Odd")
Solution 3: Pass or Fail
marks = 65
if marks >= 40:
print("Pass")
else:
print("Fail")
Solution 4: Age Classification
age = 15
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
Solution 5: Largest of Two Numbers
a = 45
b = 30
if a > b:
print("Largest:", a)
elif b > a:
print("Largest:", b)
else:
print("Both numbers are equal")
Solution 6: Largest of Three Numbers
a = 45
b = 70
c = 55
if a >= b and a >= c:
print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)
22. Interview Questions and Answers
Q1. What is an if statement in Python?
An if statement executes a block of code when its condition evaluates to a truthy value.
Q2. What is the purpose of an else statement?
The else branch executes when the preceding if condition is falsy and no earlier branch has been selected.
Q3. What is elif in Python?
elif means “else if.” It checks an additional condition when the preceding conditions in the chain are false.
Q4. Can an if statement exist without else?
Yes. An if statement can be used independently when no alternative action is required.
Q5. Can we use multiple elif statements?
Yes. A conditional chain can contain multiple elif branches, followed by an optional else branch.
Q6. What is a nested if statement?
A nested if statement is a conditional statement placed inside another conditional block.
Q7. Why is indentation important in Python?
Indentation defines the statements that belong to a conditional block. Incorrect indentation can produce errors or change the program's behavior.
Q8. What happens when an if condition is false and there is no else?
The conditional block is skipped, and execution continues with the next statement outside the block.
Q9. What is the difference between multiple if statements and if-elif-else?
Independent if statements are evaluated separately, so multiple blocks can execute. An if-elif-else chain selects at most one branch.
Q10. Can logical operators be used in if statements?
Yes. The and, or, and not operators can combine or negate conditions.
Q11. What is a conditional expression?
A conditional expression selects one of two values based on a condition, as in "Pass" if marks >= 40 else "Fail".
Q12. What is the purpose of pass?
The pass statement is a placeholder that performs no operation. It can be used when a syntactically valid block is needed but no action has been implemented yet.
23. Quick Revision Checklist
- The
if statement executes a block when its condition is truthy.
- The
else statement provides an alternative block.
- The
elif keyword checks additional conditions.
- Python uses a colon after each conditional header.
- Indentation identifies the statements inside each branch.
- Comparison operators help evaluate conditions.
- Logical operators combine multiple conditions.
- Nested conditions allow dependent decisions.
- Conditional expressions provide a compact way to select between two values.
- Boundary testing helps detect mistakes in conditions.
- Validating user input helps prevent unexpected errors.
24. Conclusion
Conditional statements are a fundamental part of Python programming. The if, if-else, and if-elif-else structures allow programs to evaluate conditions and select the appropriate actions.
By combining conditional statements with comparison operators, logical operators, user input, and nested conditions, developers can build practical programs for validation, grading, authentication workflows, financial calculations, and many other applications.
Practice writing conditions, test both true and false outcomes, and pay close attention to indentation and boundary values. These habits will help you develop clear, reliable Python programs.
Learn Python with JustAcademy
Continue developing your Python programming skills with these resources: