Introduction
Python provides the if-else statement that allows a program to execute one block of code when a condition is true and another block of code when the condition is false.
The if-else statement is one of the most commonly used control flow structures in Python. It helps programs make intelligent decisions and respond dynamically to user input and changing data.
What is Python If-Else Statement?
The Python if-else statement is a conditional statement that executes one block of code when a condition is true and another block of code when the condition is false.
Example:
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
Output:
In this example:
- The condition age >= 18 is checked.
- If the condition is true, the first block executes.
- If the condition is false, the else block executes.
Why Use If-Else Statements?
If-else statements are used to:
- Make decisions in programs
- Execute alternative actions
- Validate user input
- Handle different scenarios
- Improve application logic
- Create interactive applications
Note: Without if-else statements, programs would not be able to choose between different actions.
Syntax
The basic syntax of an if-else statement is:
if condition:
# code block if condition is true
else:
# code block if condition is false
Syntax Breakdown
- if checks a condition.
- else provides an alternative action.
- A colon (:) follows both keywords.
- Indentation defines the code blocks.
Flow of Execution
- Python evaluates the condition.
- If the condition is True, the if block executes.
- If the condition is False, the else block executes.
- Only one block runs.
Simple If-Else Example
number = 10
if number > 0:
print("Positive Number")
else:
print("Negative Number")
Output:
Since the number is greater than zero, the if block executes.
Example: Even or Odd Number
number = 7
if number % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output:
The modulus operator checks whether the remainder is zero.
Example: Pass or Fail
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")
Output:
This type of condition is common in educational applications.
Using Comparison Operators
If-else statements often use comparison operators.
| Operator | Description |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
Example:
salary = 50000
if salary > 40000:
print("Eligible")
else:
print("Not Eligible")
Output:
Using Logical Operators
Logical operators can combine multiple conditions.
| Operator | Description |
|---|---|
| and | Both conditions must be true |
| or | At least one condition must be true |
| not | Reverses the condition |
Example Using AND
age = 25
if age >= 18 and age <= 60:
print("Working Age Group")
else:
print("Not Working Age Group")
Output:
Example Using OR
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
else:
print("Weekday")
Output:
Example Using NOT
is_logged_in = False
if not is_logged_in:
print("Please Login")
else:
print("Welcome")
Output:
If-Else with Boolean Values
Boolean values work directly with if-else statements.
is_member = True
if is_member:
print("Premium Access")
else:
print("Standard Access")
Output:
If-Else with User Input
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to Vote")
else:
print("Not Eligible to Vote")
Output:
Not Eligible to Vote
This demonstrates how user input can influence program behavior.
Multiple Statements in If-Else Blocks
Both if and else blocks can contain multiple statements.
balance = 10000
withdraw = 5000
if withdraw <= balance:
print("Transaction Successful")
print("Please Collect Cash")
else:
print("Insufficient Balance")
print("Transaction Cancelled")
Output:
Please Collect Cash
Nested If-Else Statement
An if-else statement can be placed inside another if statement.
age = 22
if age >= 18:
if age >= 21:
print("Eligible for Adult Membership")
else:
print("Eligible for Basic Membership")
else:
print("Not Eligible")
Output:
Real-Life Examples:
1. Online Shopping Discount
Suppose an e-commerce website offers a discount on purchases above ₹5000.
purchase_amount = 6000
if purchase_amount >= 5000:
print("Discount Applied")
else:
print("No Discount")
Output:
This logic is commonly used in shopping applications.
2. ATM Withdrawal
balance = 8000
withdraw_amount = 10000
if withdraw_amount <= balance:
print("Withdrawal Successful")
else:
print("Insufficient Funds")
Output:
Banks use similar conditions before processing transactions.
3. Login Verification
username = "admin"
password = "1234"
if username == "admin" and password == "1234":
print("Login Successful")
else:
print("Invalid Credentials")
Output:
Login systems rely heavily on if-else statements.
4. Product Availability
stock = 0
if stock > 0:
print("Product Available")
else:
print("Out of Stock")
Output:
This condition is frequently used in inventory management systems.
Advantages of If-Else Statements
1. Decision Making
Allows programs to choose between alternatives.
2. Better User Experience
Applications can respond differently based on user actions.
3. Improved Program Logic
Makes code easier to understand and manage.
4. Flexible Execution
Different outcomes can be handled efficiently.
5. Essential for Real-World Applications
Used in banking, e-commerce, healthcare, and many other industries.
Common Mistakes
1. Missing Colon
Incorrect:
age = 20
if age >= 18
print("Adult")
else:
print("Minor")
Output:
Correct:
if age >= 18:
print("Adult")
else:
print("Minor")
2. Incorrect Indentation
Incorrect:
if age >= 18:
print("Adult")
else:
print("Minor")
Output:
Correct:
if age >= 18:
print("Adult")
else:
print("Minor")
3. Using = Instead of ==
Incorrect:
if age = 18:
print("Adult")
Output:
Correct:
if age == 18:
print("Adult")
4. Forgetting Type Conversion
Incorrect:
age = input("Enter age: ")
if age >= 18:
print("Adult")
Output:
Correct:
age = int(input("Enter age: "))
5. Writing Unnecessary Conditions
Incorrect:
if is_logged_in == True:
print("Welcome")
Better:
if is_logged_in:
print("Welcome")
Conclusion
The Python if-else statement is one of the most important decision-making structures in programming. It allows a program to execute different blocks of code depending on whether a condition is true or false. This capability makes applications dynamic, interactive, and capable of handling real-world scenarios effectively.