Python – Conditional Statements (if, elif, else) #
Conditional statements are the backbone of decision-making in programming. They allow your Python programs to execute certain blocks of code based on whether specific conditions are met. This guide will delve into Python’s conditional statements: if
, elif
, and else
, providing detailed explanations and practical examples.
Table of Contents #
- Introduction to Conditional Statements
if
Statementelif
Statementelse
Statement- Combining
if
,elif
, andelse
- Nested Conditional Statements
- Logical Operators in Conditions
- Best Practices
- Common Mistakes to Avoid
- Conclusion
1. Introduction to Conditional Statements #
Conditional statements allow your program to perform different actions based on different conditions. They enable decision-making, making your code dynamic and responsive to varying inputs or states.
In Python, the primary conditional statements are:
if
: Executes a block of code if a specified condition is true.elif
(short for “else if”): Checks another condition if the previousif
orelif
conditions were false.else
: Executes a block of code if none of the precedingif
orelif
conditions were true.
2. if
Statement #
Syntax #
if condition:
# code block to execute if condition is True
if
: The keyword that starts the conditional statement.condition
: A boolean expression that evaluates toTrue
orFalse
.- Code Block: Indented block of code that runs if the condition is
True
.
Example #
# Example of an if statement
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
Explanation:
- The condition
age >= 18
is evaluated. - Since
age
is18
, which is equal to18
, the condition isTrue
. - Therefore, the message “You are eligible to vote.” is printed.
3. elif
Statement #
Syntax #
if condition1:
# code block if condition1 is True
elif condition2:
# code block if condition1 is False and condition2 is True
elif
: Stands for “else if,” allowing multiple conditions to be checked sequentially.- You can have multiple
elif
statements following anif
.
Example #
# Example of using elif
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
Output:
Grade: B
Explanation:
- First, the condition
score >= 90
is checked. Sincescore
is85
, this isFalse
. - The
elif
conditionscore >= 80
is then checked. Since85 >= 80
isTrue
, “Grade: B” is printed. - No further conditions are checked after a
True
condition is met.
4. else
Statement #
Syntax #
if condition1:
# code block if condition1 is True
elif condition2:
# code block if condition1 is False and condition2 is True
else:
# code block if all above conditions are False
else
: Captures any case where none of the precedingif
orelif
conditions areTrue
.- There can only be one
else
statement in a conditional block, and it must come last.
Example #
# Example of using else
temperature = 30
if temperature > 30:
print("It's a hot day.")
elif temperature > 20:
print("It's a nice day.")
else:
print("It's cold.")
Output:
It's a nice day.
Explanation:
temperature > 30
isFalse
since30
is not greater than30
.temperature > 20
isTrue
since30 > 20
.- Therefore, “It’s a nice day.” is printed.
- The
else
block is skipped because aTrue
condition was already met.
5. Combining if
, elif
, and else
#
You can combine if
, multiple elif
, and else
to handle various conditions sequentially.
Example #
# Comprehensive example using if, elif, and else
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
elif day == "Friday":
print("It's almost the weekend.")
else:
print("It's a weekday.")
Output:
It's the weekend!
Explanation:
- The
if
condition checks ifday
is either “Saturday” or “Sunday”. Sinceday
is “Sunday”, it’sTrue
. - “It’s the weekend!” is printed.
- The
elif
andelse
blocks are not evaluated because aTrue
condition was already met.
6. Nested Conditional Statements #
Conditional statements can be nested within each other to handle more complex decision-making scenarios.
Example #
# Example of nested if statements
number = 15
if number > 0:
print("The number is positive.")
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
else:
print("The number is not positive.")
Output:
The number is positive.
The number is odd.
Explanation:
- The first
if
checks ifnumber > 0
. Since15 > 0
, it’sTrue
, and “The number is positive.” is printed. - Inside the first
if
, there’s anotherif
that checks ifnumber % 2 == 0
(i.e., if the number is even). - Since
15 % 2
is1
, the condition isFalse
, so theelse
block executes, printing “The number is odd.”
7. Logical Operators in Conditions #
Logical operators allow you to combine multiple conditions within a single if
, elif
, or else
statement. The primary logical operators in Python are and
, or
, and not
.
Operators #
Operator | Description | Example |
---|---|---|
and | Returns True if both operands are True . | if a > 0 and b > 0: |
or | Returns True if at least one operand is True . | if a > 0 or b > 0: |
not | Reverses the boolean value of the operand. | if not a > 0: |
Example #
# Example using logical operators
username = "admin"
password = "secret123"
if username == "admin" and password == "secret123":
print("Access granted.")
elif username == "admin" and not password == "secret123":
print("Incorrect password.")
else:
print("Invalid username.")
Output:
Access granted.
Explanation:
- The first
if
condition checks if bothusername
is “admin” andpassword
is “secret123”. Both conditions areTrue
, so “Access granted.” is printed. - The
elif
andelse
blocks are not evaluated because theif
condition was met.
8. Best Practices #
- Use Meaningful Conditions: Ensure your conditions are clear and meaningful to enhance readability.pythonCopy code
# Good if user_age >= 18: print("Eligible for voting.") # Bad if a >= 18: print("Eligible for voting.")
- Limit Nesting: Avoid deep nesting of conditional statements as it can make code hard to read. Consider using logical operators or refactoring code.pythonCopy code
# Deep nesting (Not Recommended) if condition1: if condition2: if condition3: do_something() # Refactored with logical operators if condition1 and condition2 and condition3: do_something()
- Use
elif
Instead of Multipleif
: When checking multiple exclusive conditions, useelif
to ensure only one block is executed.pythonCopy code# Using elif if score >= 90: grade = 'A' elif score >= 80: grade = 'B' else: grade = 'C' # Using multiple if (Not Recommended for exclusive conditions) if score >= 90: grade = 'A' if score >= 80: grade = 'B' else: grade = 'C'
- Keep It Simple: Aim for simplicity in your conditions to make the code easy to understand and maintain.
- Use Parentheses for Clarity: When combining multiple logical operators, use parentheses to make the order of evaluation explicit.pythonCopy code
if (age >= 18 and has_license) or is_supervisor: allow_entry()
9. Common Mistakes to Avoid #
- Incorrect Indentation: Python relies on indentation to define code blocks. Improper indentation can lead to
IndentationError
or unexpected behavior.pythonCopy code# Incorrect Indentation if condition: print("Condition is True") # This will raise an IndentationError
- Using Assignment
=
Instead of Equality==
: The single=
is for assignment, while==
is for comparison.pythonCopy code# Incorrect if x = 10: print("x is 10") # Correct if x == 10: print("x is 10")
- Forgetting the Colon
:
: Eachif
,elif
, andelse
statement must end with a colon.pythonCopy code# Incorrect if x > 0 print("Positive") # Correct if x > 0: print("Positive")
- Overusing Nested Conditionals: Deeply nested conditionals can make code hard to read and maintain. Use logical operators or refactor when possible.
- Not Covering All Cases: Ensure that all possible scenarios are handled, especially when using
if
,elif
, andelse
. - Logical Errors in Conditions: Ensure that the logical conditions accurately represent the intended logic.pythonCopy code
# Logical Error if age > 18 and age < 65: print("Working age.") # Intended to include 18 and 65 if age >= 18 and age <= 65: print("Working age.")
10. Conclusion #
Conditional statements are fundamental to controlling the flow of your Python programs. By effectively using if
, elif
, and else
, you can create dynamic and responsive applications that react appropriately to different inputs and states.
Key Takeaways:
if
: Checks a condition and executes a block of code if it’sTrue
.elif
: Checks another condition if the previousif
orelif
wasFalse
.else
: Executes a block of code if all preceding conditions areFalse
.- Logical Operators: Combine multiple conditions for more complex decision-making.
- Best Practices: Keep conditions clear, limit nesting, and use
elif
appropriately. - Avoid Common Mistakes: Watch out for indentation errors, misuse of operators, and logical inaccuracies.
Mastering conditional statements will enhance your ability to write effective and efficient Python code, enabling you to tackle a wide range of programming challenges.