Nearby lessons

45 of 108

Python - If-Else Statement

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:
    statements

Basic Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Even Number

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_false

This is useful when only a simple one-line choice is needed.

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!Python - Nested If