# Without walrus
name = input('Name: ')
if name:
print(f'Hello, {name}')
# With walrus
if (name := input('Name: ')):
print(f'Hello, {name}')# Without walrus — duplicated input() call
while True:
line = input('> ')
if line == 'quit':
break
print(f'You said: {line}')
# With walrus — cleaner
while (line := input('> ')) != 'quit':
print(f'You said: {line}')import re
text = 'foo123bar456baz789'
# Without walrus — calls int() twice!
big = [int(m) for m in re.findall(r'\d+', text) if int(m) > 200]
# With walrus — int() called once
big = [n for m in re.findall(r'\d+', text) if (n := int(m)) > 200]
# [456, 789]import json
# Without walrus — parse twice or use temp var
data = None
raw = get_response()
if raw:
data = json.loads(raw)
if data and 'name' in data:
print(data['name'])
# With walrus
if (raw := get_response()) and (data := json.loads(raw)) and 'name' in data:
print(data['name'])# Filter and transform in one pass
def get_values():
yield 5
yield 15
yield 3
yield 25
yield 8
# Without walrus — need helper function or two passes
result = [processed for v in get_values()
if (processed := v * 2) > 10]
# [30, 50, 16]# GOOD: Reduces duplication
if (match := pattern.search(text)):
print(match.group())
# BAD: Overly complex, hard to read
if (a := foo()) and (b := bar(a)) and (c := baz(b)):
process(c)
# BETTER: Split into clear steps
a = foo()
if not a:
return
b = bar(a)
if not b:
return
c = baz(b)
if c:
process(c)Create a function `process_data(data)` that: 1) Uses walrus in a while loop to process user input until 'done'. 2) Uses walrus in a list comprehension to filter and transform numbers (double them, keep only > 10). 3) Uses walrus in an if chain to check if a string matches a pattern and extract the match. 4) Uses walrus to find the first even number in a list and print it, without a separate variable declaration.