Skip to content

Commit 26c8c1c

Browse files
authored
Merge pull request #566 from realpython/walrus
Add materials for Walrus tutorial
2 parents 5dd42f8 + f9bcef9 commit 26c8c1c

File tree

4 files changed

+123
-0
lines changed

4 files changed

+123
-0
lines changed

python-walrus-operator/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# The Walrus Operator: Python's Assignment Expressions
2+
3+
This folder contains the sample code used in the RealPython tutorial [The Walrus Operator: Python's Assignment Expressions](https://realpython.com/python-walrus-operator/).
4+
5+
## About the Author
6+
7+
Geir Arne Hjelle - Email: [email protected]
8+
9+
## License
10+
11+
Distributed under the MIT license. See `LICENSE` for more information.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
numbers = [7, 6, 1, 4, 1, 8, 0, 6]
2+
3+
4+
def slow(number):
5+
print(f"Slowly calculating {number} - 2 = {number - 2}")
6+
return number - 2
7+
8+
9+
print("\nList Comprehension:")
10+
results = [slow(num) for num in numbers if slow(num) > 0]
11+
print(results)
12+
13+
print("\nLoop")
14+
results = []
15+
for num in numbers:
16+
value = slow(num)
17+
if value > 0:
18+
results.append(value)
19+
print(results)
20+
21+
print("\nfilter()")
22+
results = list(filter(lambda value: value > 0, (slow(num) for num in numbers)))
23+
print(results)
24+
25+
print("\nDouble List Comprehension")
26+
results = [value for num in numbers for value in [slow(num)] if value > 0]
27+
print(results)
28+
29+
print("\nList Comprehension with Walrus Operator")
30+
results = [value for num in numbers if (value := slow(num)) > 0]
31+
print(results)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import random
2+
import string
3+
4+
QUESTIONS = {
5+
"What is the formal name of PEP 572?": [
6+
"Assignment Expressions",
7+
"Named Expressions",
8+
"The Walrus Operator",
9+
"The Colon Equals Operator",
10+
],
11+
"Which one of these is an invalid use of the walrus operator?": [
12+
"[y**2 for x in range(10) if y := f(x) > 0]",
13+
"print(y := f(x))",
14+
"(y := f(x))",
15+
"any((y := f(x)) for x in range(10))",
16+
],
17+
}
18+
19+
num_correct = 0
20+
for question, answers in QUESTIONS.items():
21+
correct = answers[0]
22+
random.shuffle(answers)
23+
24+
coded_answers = dict(zip(string.ascii_lowercase, answers))
25+
valid_answers = sorted(coded_answers.keys())
26+
27+
for code, answer in coded_answers.items():
28+
print(f" {code}) {answer}")
29+
30+
while (user_answer := input(f"\n{question} ")) not in valid_answers:
31+
print(f"Please answer one of {', '.join(valid_answers)}")
32+
33+
if coded_answers[user_answer] == correct:
34+
print(f"Correct, the answer is {user_answer!r}\n")
35+
num_correct += 1
36+
else:
37+
print(f"No, the answer is {correct!r}\n")
38+
39+
print(f"You got {num_correct} correct out of {len(QUESTIONS)} questions")

python-walrus-operator/wc.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import pathlib
2+
import sys
3+
4+
5+
def count_words_1(filenames):
6+
for filename in filenames:
7+
path = pathlib.Path(filename)
8+
counts = (
9+
path.read_text().count("\n"), # Number of lines
10+
len(path.read_text().split()), # Number of words
11+
len(path.read_text()), # Number of characters
12+
)
13+
print(*counts, path)
14+
15+
16+
def count_words_2(filenames):
17+
for filename in filenames:
18+
path = pathlib.Path(filename)
19+
counts = (
20+
(text := path.read_text()).count("\n"), # Number of lines
21+
len(text.split()), # Number of words
22+
len(text), # Number of characters
23+
)
24+
print(*counts, path)
25+
26+
27+
def count_words_3(filenames):
28+
for filename in filenames:
29+
path = pathlib.Path(filename)
30+
text = path.read_text()
31+
counts = (
32+
text.count("\n"), # Number of lines
33+
len(text.split()), # Number of words
34+
len(text), # Number of characters
35+
)
36+
print(*counts, path)
37+
38+
39+
if __name__ == "__main__":
40+
count_words_1(sys.argv[1:])
41+
count_words_2(sys.argv[1:])
42+
count_words_3(sys.argv[1:])

0 commit comments

Comments
 (0)