ifIntermediate Examples

Starts a conditional statement; executes block only if condition is true

Conditional expressions (ternary)

One-line if/else for concise assignments.

python
# Ternary expression
x = 42
label = "even" if x % 2 == 0 else "odd"
print(f"{x} is {label}")

# Nested ternary (use sparingly)
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(f"Score {score}: Grade {grade}")

# In list comprehensions
nums = range(1, 11)
labels = [f"{n}: {'even' if n % 2 == 0 else 'odd'}" for n in nums]
print(labels[:4])

The ternary expression 'x if condition else y' is useful in assignments and comprehensions. Avoid nesting more than one level.

Short-circuit evaluation

How 'and' and 'or' work with if.

python
# 'and' returns first falsy or last value
print(1 and 2 and 3)
print(1 and 0 and 3)

# 'or' returns first truthy or last value
print(0 or "" or "fallback")
print("first" or "second")

# Practical: safe dictionary access
config = {}
debug = config.get("debug") or False
print(f"Debug: {debug}")

# Guard pattern
items = [1, 2, 3]
if items and items[0] > 0:
    print("First item is positive")

Python short-circuits: 'and' stops at the first falsy value, 'or' stops at the first truthy value. The guard pattern 'if items and items[0]' prevents IndexError on empty lists.

Want to try these examples interactively?

Open Intermediate Playground