-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path44_walrus_operator.py
More file actions
54 lines (44 loc) · 1.22 KB
/
44_walrus_operator.py
File metadata and controls
54 lines (44 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# --------------------------
# Walrus Operator
# --------------------------
"""
It’s := introduced in Python 3.8.
It allows you to assign a value to a variable while using it in an expression.
Can’t use it at the top level (like x := 5 by itself). Must be inside an expression.
Use for clarity, not cleverness — overuse makes code confusing.
"""
# without
value = input("Enter something: ")
if value != "":
print(f"You typed: {value}")
# with walrus operator
if (value := input("Enter something: ")) != "":
print(f"You typed: {value}")
# Example 1: While Loop
# Old way:
line = input("Enter text: ")
while line != "":
print(f"You said: {line}")
line = input("Enter text: ")
# Walrus way:
while (line := input("Enter text: ")) != "":
print(f"You said: {line}")
# Example 2: Filtering in Comprehensions
# Old way:
results = []
for num in range(10):
square = num * num
if square > 10:
results.append(square)
print(results)
# Walrus way:
results = [square for num in range(10) if (square := num * num) > 10]
print(results)
# Example 3: Avoiding Duplicate Function Calls
# Old way:
name="Gennie"
if len(name) > 5:
print(len(name))
# Walrus way:
if (name_length := len(name)) > 5:
print(name_length)