Nearby lessons
39 of 159Python - If-Else Statement
📌 What You Will Learn
- Define the if-else statement and when to use it
- Write the syntax of if-else with proper indentation
- Apply if-else in real-world examples like age validation and password checks
- Use nested if-else when one decision depends on another
- Use the short-hand ternary operator value_if_true if condition else value_if_false
What Is if-else?
The if-else statement chooses between two blocks of code.
One block runs when the condition is true, and the other runs when it is false.
Only one of the two blocks executes at a time.
Syntax
if condition:
statements
else:
statementsBasic Example
If the condition changes to false, the else block runs instead.
More Examples
- Age validation for voting
- Password checks
- Positive or negative number checks
- Boolean flag handling
- Handling login success and failure messages
Nested if-else
We can place an if-else block inside another condition when one decision
depends on another.
Short Hand if-else
Python also supports a short-hand form called the ternary operator:
value_if_true if condition else value_if_falseThis is useful when only a simple one-line choice is needed.
📝 Key Takeaways
- The if-else statement chooses between two blocks of code
- Only one of the two blocks executes at a time
- The if block runs when the condition is True and the else block runs when it is False
- Nested if-else places one condition inside another
- The ternary operator is a one-line short-hand for if-else
🧠 Test Your Knowledge
5 QuestionsProgress: 0 / 5