ifAdvanced Examples

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

Walrus operator in conditions

Using := to assign and test in one expression (Python 3.8+).

python
# Without walrus
import re
text = "Call us at 555-1234 for info"
match = re.search(r'\d{3}-\d{4}', text)
if match:
    print(f"Found: {match.group()}")

# With walrus operator
if m := re.search(r'\d{3}-\d{4}', text):
    print(f"Found: {m.group()}")

# In while loops
data = [1, 2, 3, 0, 4, 5]
it = iter(data)
while (val := next(it, None)) is not None:
    if val == 0:
        break
    print(val, end=" ")
print()

The walrus operator := assigns a value and returns it in one expression. It reduces redundancy in patterns where you check and use the same value.

Want to try these examples interactively?

Open Advanced Playground