Q1Which of the following runs the block of if not value:?
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
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.
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
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.
| Type | Treated as False | Treated as True (examples) |
|---|---|---|
| int / float | 0, 0.0 | 1, -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"} |
| None | None | (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)
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.
# 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.
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")
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.
# 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:.
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")
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.
Knowledge Check
Answer each question one by one.
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?