Part of Python for Beginners

Python Conditionals Explained - if, elif, else, and, or, not | Beginner Tutorial #6

Sandy LaneSandy Lane

Video: Python Conditionals Explained - if, elif, else, and, or, not | Beginner Tutorial #6 by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Python Conditionals: if, elif, else

if, elif, else. and, or, not for combining. Indentation matters — Python uses it instead of braces. The truthiness rules apply (lesson 2).

Python's conditional syntax is the cleanest in any C-family language — no braces, no extra parens, just colons and indentation.

The basic shape

age = int(input("Enter your age: "))

if age >= 18:
  print("You are an adult")
elif age >= 13:
  print("You are a teenager")
else:
  print("You are a child")

Three keywords: if, elif (else-if), else. Each followed by a colon. The body is indented.

Output for input 20:

You are an adult

Indentation, not braces

# Python:
if x > 0:
    print("positive")
    print("really positive")

# C:
if (x > 0) {
    printf("positive\n");
    printf("really positive\n");
}

Python uses indentation to delimit blocks. Same indentation level = same block. Different indentation = different block.

Convention: 4-space indents. Some codebases use 2 spaces. Don't mix tabs and spaces — Python errors on mixed indentation.

Comparison operators

x == y    # equal
x != y    # not equal
x < y     # less than
x > y     # greater than
x <= y    # less than or equal
x >= y    # greater than or equal

Standard, all return booleans.

Two extras Python has that C doesn't:

x == y == z          # chained: same as (x == y) and (y == z)
1 < x < 10           # chained: equivalent to (1 < x) and (x < 10)
"a" in "apple"       # membership
4 in [1, 2, 3, 4]    # membership in list

Chained comparisons are idiomatic in Python — read left to right.

Logical operators

temp = int(input("Temperature (F): "))
is_raining = input("Is it raining? (yes/no): ")

if temp > 85 and not is_raining == "yes":
  print("Hot and dry — go to the pool!")
elif temp > 85 and is_raining == "yes":
  print("Hot and rainy — stay inside")
elif temp < 50 or is_raining == "yes":
  print("Cold or rainy — stay inside")
else:
  print("Nice weather — go for a walk!")

and, or, not — keywords, not symbols. Compare to C's &&, ||, !.

and/or short-circuit: if the first operand decides the result, the second isn't evaluated. Useful for null-safe access:

if obj is not None and obj.name == "Alice":
  ...   # safe — obj.name only evaluates if obj exists

A small quiz game

print("Python Quiz Game!")
score = 0

answer = input("Q1: What keyword starts a condition? ")
if answer == "if" or answer == "If":
  print("Correct!")
  score = score + 1
else:
  print("Wrong! Answer: if")

answer = input("Q2: True and False are called? ")
if answer == "booleans" or answer == "Booleans":
  print("Correct!")
  score = score + 1
else:
  print("Wrong! Answer: booleans")

print(f"Your score: {score}/2")

For more answer variations, normalize first:

answer = input("Q1: ").strip().lower()
if answer == "if":
  ...

strip().lower() handles whitespace + case. Better than enumerating every variation.

Truthy and falsy

if 0:        # False — zero is falsy
    ...
if "":       # False — empty string
    ...
if []:       # False — empty list
    ...
if None:     # False
    ...
if 1:        # True
    ...
if "hi":     # True
    ...

Python's truthiness rules:

  • Falsy: False, 0, 0.0, "", [], (), {}, None.
  • Truthy: everything else.

This lets you write idiomatic checks:

if my_list:           # checks "non-empty"
    print("has items")

if name:              # checks "non-empty string"
    print(f"Hello, {name}")

vs:

if len(my_list) > 0:  # works but more verbose
    ...

Nested ifs

if age >= 18:
  if has_id:
    print("Welcome")
  else:
    print("Need ID")
else:
  print("Too young")

Each level adds indentation. Often and makes it cleaner:

if age >= 18 and has_id:
  print("Welcome")
elif age >= 18:
  print("Need ID")
else:
  print("Too young")

Single-line if

print("Adult" if age >= 18 else "Minor")

Conditional expression: value_if_true if condition else value_if_false. Same as ternary in C.

For one-line decisions, this is cleaner than a 4-line if/else.

== vs is

x = [1, 2, 3]
y = [1, 2, 3]
z = x

x == y    # True (same content)
x is y    # False (different objects)
x is z    # True (same object — z = x didn't copy)

== checks value equality. is checks identity (same memory location).

Use == for value comparisons. Use is only for is None, is True, is False — singleton checks.

match (Python 3.10+)

match status:
    case 200:
        print("OK")
    case 404:
        print("Not found")
    case 500 | 502 | 503:
        print("Server error")
    case _:
        print("Unknown")

Python's pattern matching, added in 3.10. More powerful than switch in C — supports type matching, destructuring, etc.

For older Python (3.9 and below), use if/elif chains.

Common stumbles

= instead of ==. Single = is assignment; if x = 5: is a syntax error. Use == for comparison.

Inconsistent indentation. Mix tabs and spaces → IndentationError. Configure your editor to use spaces only.

Forgetting the colon. if x: ✓. if x ✗ — SyntaxError.

Comparing strings with is. s is "hello" may or may not work depending on Python's string interning. Always use == for strings.

Treating None as falsy when value matters. if x: is True for x = "hi" but also for x = "0". For "is x set," use if x is not None:.

if not x in lst. Works but the canonical form is if x not in lst.

What's next

Lesson 7: loops. for with range(), while, enumerate(), break, continue.

Recap

if/elif/else with colon and indentation. and/or/not keywords. Chained comparisons (1 < x < 10). Truthy/falsy: 0, empty containers, None are falsy. == for value equality, is for identity (use only for None/True/False checks). Conditional expression a if cond else b for one-line ternary. Pattern matching with match/case in 3.10+.

Next lesson: loops.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.