DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Understanding if, elif, and else in Python with Simple Examples

Conditional statements let your code make decisions. Python uses if, elif, and else to handle different situations based on conditions.

The basic if statement

An if statement checks a condition. If the condition is True, the code block inside runs.

age = 18

if age >= 18:
    print("You can vote.")
Enter fullscreen mode Exit fullscreen mode

The colon : is required after the condition. The indented lines (usually 4 spaces) form the code block that runs when the condition is True.

If the condition is False, the block is skipped.

Adding else

Use else to specify what happens when the if condition is False.

age = 16

if age >= 18:
    print("You can vote.")
else:
    print("You cannot vote yet.")
Enter fullscreen mode Exit fullscreen mode

No condition is needed after else.

Using elif for multiple conditions

For more than two possibilities, use elif (short for "else if") to check additional conditions.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")
Enter fullscreen mode Exit fullscreen mode

Python checks the conditions from top to bottom and runs only the first block where the condition is True.

Common examples

Check if a number is positive, negative, or zero:

number = -5

if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")
Enter fullscreen mode Exit fullscreen mode

Combine multiple conditions with and, or, and not:

temperature = 25
is_raining = False

if temperature > 30 and not is_raining:
    print("Great day for the beach!")
else:
    print("Maybe stay inside.")
Enter fullscreen mode Exit fullscreen mode

Important notes

  • Always include the colon : after if, elif, and else.
  • Keep indentation consistent (Python uses it to define code blocks).
  • Only one block executes: the first True condition (or else if none are True).

Quick summary

  • if checks the first condition.
  • elif adds more conditions to check.
  • else handles all remaining cases.
  • Indentation defines the code blocks.

Practice writing simple programs that make decisions. Conditional statements form the basis of logic in Python programs.

Top comments (0)