Python if...else Statement
Learn Python through interactive, bite-sized lessons. Practice with real code challenges and build projects step-by-step.
Start Python Journey →The if...else statement is a crucial control flow structure in Python. It allows programmers to execute different code blocks based on specific conditions.
Basic Syntax
The basic syntax of an if...else statement in Python is as follows:
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
How It Works
When Python encounters an if...else statement, it evaluates the condition. If the condition is True, the code block under the if statement executes. Otherwise, the code block under the else statement runs.
Example
Here's a simple example demonstrating the use of if...else:
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
In this example, if the age is 18 or greater, the first message is printed. Otherwise, the second message appears.
Multiple Conditions: elif
For more complex decision-making, Python provides the elif (else if) keyword. It allows you to check multiple conditions:
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
This structure evaluates conditions in order, executing the block of the first true condition.
Best Practices
- Keep conditions simple and readable
- Use Python Indentation consistently
- Consider using Python Match Case Statements for complex conditions
- Combine with Python Logical Operators for more sophisticated checks
Related Concepts
To further enhance your understanding of control flow in Python, explore these related topics:
Mastering if...else statements is crucial for writing efficient and logical Python programs. Practice with various conditions to solidify your understanding of this fundamental concept.