Conditional Statements: if-else (Part 2)
Following our exploration of Conditional Statements: if (Part 1), this article delves into the if-else statement, which allows you to execute a different block of code when the if condition is not met.
📚 Prerequisites
A basic understanding of Python's if statement.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ The syntax of the
if-elsestatement. - ✅ How to use the
if-elsestatement to handle alternative paths. - ✅ The ternary operator for concise
if-elsestatements.
🧠 Section 1: The if-else Statement
The if-else statement allows you to execute one block of code if a condition is True, and another block of code if the condition is False.
Syntax:
if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
💻 Section 2: Handling Alternative Paths
Let's look at an example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
In this example, the condition age >= 18 is False, so the code inside the else block is executed.
🛠️ Section 3: The Ternary Operator
Python provides a concise way to write simple if-else statements on a single line, known as the ternary operator or conditional expression.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 20
message = "Adult" if age >= 18 else "Minor"
print(message) # Output: Adult
The ternary operator is a great way to make your code more compact, but it's best used for simple conditions. For more complex logic, a standard if-else statement is more readable.
💡 Conclusion & Key Takeaways
You've now learned how to use the if-else statement to create more powerful conditional logic in your Python programs.
Let's summarize the key takeaways:
if-elseStatement: Executes one block of code if a condition isTrue, and another if it'sFalse.- Ternary Operator: A concise way to write simple
if-elsestatements.
Challenge Yourself: Write a script that takes a number as input and prints whether it's even or odd.
➡️ Next Steps
In the next article, we'll continue our exploration of conditional statements with "Conditional Statements: if-elif-else (Part 3)".
Happy coding!
Glossary (Python Terms)
- Ternary Operator: A conditional expression that allows you to write a simple
if-elsestatement on a single line.