PythonBeginner 12 min Lesson 7 of 30

Day 7 — Conditions

Make decisions in code with if, elif and else. Understand comparison operators, and/or/not, truthiness, and why deep nesting is worth avoiding.

Python · Lesson 7 of 30
0/30 done(0%)

What is it? #

A condition lets your program take different paths. Python evaluates an expression, decides whether it is true or false, and runs the matching block.

The block is defined by indentation. Everything indented under an if belongs to it, and the first line back at the outer level is outside it again.

elif means "otherwise, check this instead". Python tries each branch in order and stops at the first true one. else catches everything that did not match.

Python also treats non-boolean values as true or false in a condition. Empty things — 0, "", [], {}, None — count as false. Everything else counts as true. This is called truthiness, and it makes code shorter while occasionally surprising you.

Think of it like this #

Think of airport security lanes. A staff member checks the first rule: "do you have priority boarding?" If yes, you go left and the checking stops. If not, they check the next rule, then the next. else is the general lane that takes whoever is left.

Simple example #

An order needs a shipping charge. Orders over 999 ship free, orders from members ship at a discount, and everything else pays the standard rate. The rules are checked in order of priority.

Code #

PYTHON
total = 750
is_member = True
coupon = ""

if total > 999:
    shipping = 0
elif is_member:
    shipping = 40
else:
    shipping = 80

print("Shipping:", shipping)          # Shipping: 40

# Comparison and logical operators
age = 22
has_id = True
if age >= 18 and has_id:
    print("Allowed")

if not coupon:                        # empty string is falsy
    print("No coupon applied")

# Chained comparison — valid Python
score = 76
if 70 <= score < 90:
    print("Grade B")

# Careful: falsy is not the same as missing
quantity = 0
if quantity:
    print("has quantity")             # does not run
if quantity is not None:
    print("quantity was provided")    # does run

How it works #

The first block runs top to bottom. total > 999 is false, so Python moves to elif is_member, which is true, so shipping = 40 runs and the else is skipped entirely. Only one branch ever runs in an if/elif/else chain.

age >= 18 and has_id is true only when both sides are true. Python also short-circuits: if the left side of an and is false, the right side is never evaluated. That is useful when the right side would error, such as if user is not None and user.is_active.

not coupon reads oddly at first. coupon is an empty string, which is falsy, so not coupon is true. This is the idiomatic way to check "nothing here" for strings and lists.

70 <= score < 90 is a chained comparison. Python evaluates it the way maths notation suggests, unlike most other languages where you would need two comparisons joined with and.

The last block is the trap. quantity = 0 is a real, provided value, but it is falsy, so a plain if quantity: treats it as absent. When zero, empty string or False are legitimate values, compare explicitly with is not None.

Real-world use #

Conditions are where business rules live: pricing tiers, feature flags, permission checks, validation. Because rules change often, the readability of a condition matters more than its cleverness.

Two habits help in real code. First, use guard clauses — check the bad cases early and return, instead of wrapping the happy path in three levels of indentation. Second, name complicated conditions: is_eligible_for_refund = order.paid and not order.shipped and days_since_order < 30 reads better than the same expression buried in an if.

The None versus falsy distinction causes real production bugs, particularly around quantities, prices and counts where zero is a valid answer.

Common mistakes #

  • Using = instead of == in a condition. Python raises a SyntaxError, which is kinder than languages that silently assign.
  • Treating 0, "" or [] as "missing". They are falsy but present — check is None when that distinction matters.
  • Writing if x == True:. Just write if x: — and if x is not a boolean, that comparison probably hides a bug.
  • Nesting four levels of if. Return early instead; each guard clause removes a level.
  • Forgetting that elif stops at the first match, then wondering why a later branch never runs.

Practice #

Write a function that takes a numeric score and prints a grade: 90 and above is A, 75 to 89 is B, 60 to 74 is C, below 60 is F. Then add a check that prints "invalid score" for anything below 0 or above 100 — as a guard clause at the top, not as another nested branch.

Quick quiz

  1. 1. How many branches of an if/elif/else chain can run?

  2. 2. Which of these is falsy?

  3. 3. What does short-circuiting mean for `a and b`?

  4. 4. Why is `if quantity:` risky when quantity can be 0?

  5. 5. Is `70 <= score < 90` valid Python?

Summary

  • if/elif/else runs exactly one branch — the first one that is true.
  • Indentation defines the block; there are no braces.
  • Empty values are falsy, which is handy but hides the difference between 0 and missing.
  • `and` and `or` short-circuit, which you can use to guard against errors.
  • Guard clauses beat deep nesting for readability.