Python If Else
Introduction
In programming, we often need to make decisions based on certain conditions. For example, a program might need to do one thing if a user is logged in and another if they're not. Python's conditional statements allow us to implement this decision-making logic in our code.
Conditional statements, primarily built with if
, else
, and elif
(short for "else if"), are fundamental control flow tools that execute different blocks of code depending on whether specified conditions are True
or False
.
Basic If Statement
The most basic form of conditional execution in Python is the if
statement. It executes a block of code only if a specified condition evaluates to True
.
Syntax
if condition:
# code to execute if condition is True
Example
age = 18
if age >= 18:
print("You are an adult.")
# Output: You are an adult.
In this example, the message prints because the condition age >= 18
evaluates to True
.
If-Else Statement
What if we want to execute one block of code when a condition is True
and another when it's False
? That's where the if-else
statement comes in.
Syntax
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
Example
temperature = 15
if temperature > 25:
print("It's warm outside!")
else:
print("It's not very warm today.")
# Output: It's not very warm today.
Since the temperature is 15, which is not greater than 25, the code in the else
block executes.
If-Elif-Else Statement
Often, we need to check multiple conditions. The elif
(short for "else if") statement allows us to check additional conditions if the previous conditions are not met.
Syntax
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition1 is False and condition2 is True
else:
# code to execute if both condition1 and condition2 are False
Example
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
# Output: Grade: B
In this example, the program checks multiple conditions to determine the appropriate grade based on the score.
Nested If Statements
You can also place an if
statement inside another if
statement, creating what's called a "nested if" statement.
Syntax
if condition1:
# code to execute if condition1 is True
if condition2:
# code to execute if both condition1 and condition2 are True
else:
# code to execute if condition1 is True and condition2 is False
else:
# code to execute if condition1 is False
Example
is_weekend = True
weather = "sunny"
if is_weekend:
if weather == "sunny":
print("Let's go to the beach!")
else:
print("Let's watch a movie at home.")
else:
print("It's a weekday, time to work.")
# Output: Let's go to the beach!
Conditional Expressions (Ternary Operators)
Python also supports a more concise way to express simple if-else statements called conditional expressions or ternary operators.
Syntax
value_if_true if condition else value_if_false
Example
age = 20
status = "adult" if age >= 18 else "minor"
print(status)
# Output: adult
This is equivalent to:
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
print(status)
# Output: adult
Real-World Applications
User Authentication
username = input("Enter username: ")
password = input("Enter password: ")
# In a real application, you'd check against a database
if username == "admin" and password == "password123":
print("Login successful!")
else:
print("Invalid username or password.")
# Input: admin, password123
# Output: Login successful!
Weather App
temperature = 28
if temperature > 30:
print("It's very hot! Stay hydrated.")
elif temperature > 20:
print("It's a pleasant day.")
elif temperature > 10:
print("It's a bit cool.")
else:
print("It's cold outside!")
# Output: It's a pleasant day.
Discount Calculator
total_purchase = 120
is_member = True
if is_member:
if total_purchase > 100:
discount = 0.2 # 20% discount
else:
discount = 0.1 # 10% discount
else:
if total_purchase > 100:
discount = 0.1 # 10% discount
else:
discount = 0.05 # 5% discount
final_price = total_purchase * (1 - discount)
print(f"Final price after discount: ${final_price}")
# Output: Final price after discount: $96.0
Common Mistakes and Best Practices
Indentation
Python uses indentation to define code blocks. Incorrect indentation will cause syntax errors or unexpected behavior.
# Correct indentation
if True:
print("This is properly indented.")
# Incorrect indentation - will cause an IndentationError
if True:
print("This will cause an error.")
Comparison vs. Assignment
Be careful not to use =
(assignment) when you mean ==
(comparison).
# Incorrect - assigns 10 to x and always evaluates to True
if x = 10:
print("x is 10")
# Correct - checks if x equals 10
if x == 10:
print("x is 10")
Boolean Evaluation
Remember that in Python, empty containers, zero, None
, and False
itself all evaluate to False
.
if 0:
print("This won't print because 0 is falsy")
if []:
print("This won't print because an empty list is falsy")
if "Hello":
print("This will print because a non-empty string is truthy")
# Output: This will print because a non-empty string is truthy
Summary
Conditional statements (if
, else
, and elif
) are essential tools in Python programming that allow your code to make decisions based on conditions. They enable your programs to execute different code blocks based on whether certain conditions are met.
Key points to remember:
- Use
if
to execute code when a condition isTrue
- Use
else
to execute code when theif
condition isFalse
- Use
elif
to check additional conditions - Pay attention to indentation as it defines the code blocks
- Use nested if statements for more complex conditional logic
- Consider using conditional expressions for simple if-else statements
Exercises
-
Write a program that takes a user's age and prints whether they are a child (under 13), teenager (13-19), or adult (20+).
-
Create a simple calculator that takes two numbers and an operator (
+
,-
,*
,/
) and returns the result of the operation. -
Write a program that determines whether a year entered by the user is a leap year.
-
Create a program that categorizes a person's BMI (Body Mass Index) as underweight, normal, overweight, or obese based on standard BMI ranges.
-
Implement a simple grading system that takes a numerical score and outputs a letter grade (A, B, C, D, F) based on the standard grading scale.
Additional Resources
- Python Official Documentation on Control Flow
- Real Python: Python Conditional Statements
- W3Schools Python Conditions
- Programiz Python if...else
Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)