Learn by reading through in order

if / elif / else and Advanced Branching

Get to know Python's if / elif / else and the more advanced branching tricks, all runnable directly in your browser.

The basics of if and if not

if 条件: runs the block only when the condition is True — it's the most basic branching construct. To negate a condition, prepend not, as in if not 条件:.

not is the operator that flips True and False, so phrases like "when it's not …" or "when it isn't empty" can be written naturally.

# if: runs only when the condition is True
is_logged_in = True
if is_logged_in:
    print("Welcome")
# Output: Welcome

# if not: flips the condition before evaluating
is_logged_in = False
if not is_logged_in:
    print("Please log in")
# Output: Please log in

# Combining with comparison expressions
cart = []
if not cart:
    print("Your cart is empty")
# Output: Your cart is empty

Check whether a user has verified their email.

① Define email_verified = False.

② Use if email_verified: to print "Thanks for using our service" when verified.

③ Use if not email_verified: to print "Please complete email verification" when not verified.

(The explanation appears once you run the code correctly.)

Python Editor

Run code to see output

Writing multi-way branches with elif and else

To handle several branches, use elif and else.

elif is short for else if — when the if condition is False, Python tries the next condition, and if none of them match, the final else runs.

How if / elif / else are evaluated
Startif cond1block 1elif cond2block 2elseblock 3TrueFalseTrueFalseotherwise

Conditions are evaluated from top to bottom. Only the first one that becomes True runs, and the rest are skipped. If none are True, else runs.

# Choose an instruction based on a traffic signal
signal = "YELLOW"

if signal == "GREEN":
    print("Go")
elif signal == "YELLOW":
    print("Proceed with caution")
elif signal == "RED":
    print("Stop")
else:
    print("Unknown signal")
# Output: Proceed with caution

Switch the on-screen message based on a user's role.

① Assign role = "member".

② Print "You can access the admin panel" when role == "admin", "You can access your dashboard" when role == "member", "Please log in" when role == "guest", otherwise "Unknown role".

Python Editor

Run code to see output

elif is evaluated top-to-bottom

If you write if age >= 0: ... elif age >= 20: ..., the broader condition comes first, so the later one never matches. With multi-way branches, list the narrower (stricter) conditions first.

Using a value itself as the condition (truthiness)

An if condition isn't limited to comparison expressions like == — you can place a value itself there. Python will convert it to bool behind the scenes, treating "empty" or 0 as False and everything else as True.

Truthiness of values
0 / "" /[] / {} / Nonebool conversionFalsehas contentbool conversionTrue
TypeTreated as FalseTreated as True (examples)
int / float0, 0.01, -1, 3.14
str"" (empty string)"a", "0" (any non-empty string is True)
list / tuple / set[], (), set() (empty collections)[1], (0,), {0}
dict{} (empty dict){"key": "value"}
NoneNone(every value other than None)

This behavior lets you write checks like "is the input empty?" or "is anything in the cart?" very concisely.

Instead of if len(cart) > 0:, just write if cart: — the meaning is the same. This is a very Pythonic style.

# Don't run a search when the keyword is empty
search_query = ""
if search_query:
    print(f"Searching: {search_query}")
else:
    print("Please enter a keyword")
# Output: Please enter a keyword

# Move to checkout when the cart has at least one item
cart = ["apple", "bread"]
if cart:
    print(f"Proceeding with {len(cart)} item(s)")
# Output: Proceeding with 2 item(s)

Check whether a shipping address has been registered.

① Set shipping_address = "" (an empty string).

② Use if shipping_address: — print "Ready to ship" when there's an address, otherwise print "Please register your address".

③ Reassign shipping_address to something like "100 Main St, Springfield…" and run the same if again to confirm the result changes.

Python Editor

Run code to see output

Writing one-line ifs with the ternary operator

When all you need is to assign one of two values based on a condition, you don't need 4 lines of if / else — you can do it in one line. This is called the ternary operator (or conditional expression). The form is value_if_true if condition else value_if_false.

How to read the ternary operator
value 1ifcondelsevalue 2
# 4 lines with regular if / else
age = 25
if age >= 20:
    status = "adult"
else:
    status = "minor"

# One line with the ternary operator
status = "adult" if age >= 20 else "minor"
print(status)   # adult

The trick is using it only for simple two-way choices. When the conditions or values get long, or you have three or more branches, plain if / elif / else is more readable.

Switch the shipping label based on the order total.

① Define total_price = 3200.

② Using the ternary operator, assign "Free shipping" to shipping_label when total_price >= 5000, otherwise "Shipping $5".

③ Print shipping_label.

Python Editor

Run code to see output

Range checks can be chained directly

Range checks like "0 to 100 inclusive" can be written by chaining comparison operators instead of using and. The result reads just like a math inequality, making the intent very clear.

score = 78

# Using and
if score >= 0 and score <= 100:
    print("Valid score")

# Chained form (same meaning)
if 0 <= score <= 100:
    print("Valid score")

Decide whether a test score is within the valid range (0–100).

① Define score = 78.

② Using the chained comparison 0 <= score <= 100, print "Valid score" when in range, otherwise "Out of range".

③ Reassign score = 120 and run the same check again.

Python Editor

Run code to see output

Inspecting type and value (isinstance and is None)

When you want to check the type of a value held by a variable, use isinstance(value, type). Pass the value first and the type second — if the value is an instance of that type, it returns True.

price = 980
user_name = "alice"

print(isinstance(price, int))      # True
print(isinstance(user_name, str))  # True
print(isinstance(price, str))      # False

# Combine with if to compute only when it's a number
if isinstance(price, int) and price > 0:
    tax_included = int(price * 1.1)
    print(tax_included)   # 1078

What is None?

None is Python's special value meaning "no value". It represents things like "a result that hasn't been fetched yet", "an uninitialized state", or "what a function returns when it returns nothing". It is the one and only value that means "nothing", distinct from 0 or an empty string.

How None differs from other values
0(number)""(empty string)[](empty list)None(no value)
# A function that returns nothing implicitly returns None
def greet():
    print("hello")

result = greet()      # "hello" is printed
print(result)         # None

# An initial value meaning "not decided yet"
selected_user = None
print(selected_user)  # None

To check whether a value is None, the Pythonic way is is None rather than ==. Because None is a single, unique object in the program, comparing whether two references point to the same object in memory with is makes the intent clearer.

# User info from an API (assume it hasn't been fetched yet)
user = None

if user is None:
    print("User info not loaded")
else:
    print(f"Welcome, {user}")
# Output: User info not loaded

# To check "not None", use `is not None`
score = 0
if score is not None:
    print(f"Score: {score}")   # Score: 0

0 and None are different things

Writing if score: will treat score == 0 as False as well. When you need to distinguish "not entered (None)" from "0 points", explicitly check with if score is None: or if score is not None:.

Check the presence and type of a user's age fetched from an API.

① Define user_age = None.

② If user_age is None, print "Age not registered"; otherwise, if isinstance(user_age, int) is True, print the value of user_age.

③ Reassign user_age = 29 and run the same check again.

Python Editor

Run code to see output

Checking collection contents with in / not in

To test whether a value is contained in a list, use value in collection. The opposite — "not contained" — is value not in collection. It works for lists, tuples, sets, and strings, and for dicts it checks the keys.

allowed_roles = ["admin", "editor", "member"]
current_role = "member"

if current_role in allowed_roles:
    print("Access granted")
else:
    print("Access denied")
# Output: Access granted

# Check whether a substring appears in a string
if "error" in "connection error: timeout":
    print("Detected an error line")

# For a dict, `in` checks the keys
user = {"name": "alice", "role": "admin"}
if "email" not in user:
    print("Email not registered")

Check the publication status of a blog post.

① Define published_slugs = ["python-intro", "sql-basics", "git-tips"].

② Define target = "git-tips".

③ If target is in published_slugs, print "Published"; otherwise print "Draft".

④ Change target to "draft-post" and run the same check again.

Python Editor

Run code to see output

In this article, we covered advanced branching with the basics of if / if not, multi-way logic with elif / else, truthiness that treats empty values and 0 as False, the ternary operator value_1 if condition else value_2, type and value checks with isinstance and is None, and collection checks with in / not in.

In the next article, we'll learn all() / any(), which let you check whether every element in a list satisfies a condition in a single call.

QUIZ

Knowledge Check

Answer each question one by one.

Q1Which of the following runs the block of if not value:?

Q2What does this code print?
age = 18
status = "adult" if age >= 20 else "minor"
print(status)

Q3Which of the following is the most recommended way to check whether a value is None?