Skip to content

Commit

Permalink
Add materials for Walrus tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
gahjelle committed Aug 12, 2024
1 parent 5dd42f8 commit cd9119b
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 0 deletions.
11 changes: 11 additions & 0 deletions python-walrus-operator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# The Walrus Operator: Python's Assignment Expressions

This folder contains the sample code used in the RealPython tutorial [The Walrus Operator: Python's Assignment Expressions](https://realpython.com/python-walrus-operator/).

## About the Author

Geir Arne Hjelle - Email: [email protected]

## License

Distributed under the MIT license. See `LICENSE` for more information.
33 changes: 33 additions & 0 deletions python-walrus-operator/slow_calculations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
numbers = [7, 6, 1, 4, 1, 8, 0, 6]


def slow(number):
print(f"Slowly calculating {number} - 2 = {number - 2}")
return number - 2


print("\nList Comprehension:")
results = [slow(num) for num in numbers if slow(num) > 0]
print(results)

print("\nLoop")
results = []
for num in numbers:
value = slow(num)
if value > 0:
results.append(value)
print(results)

print("\nfilter()")
results = list(
filter(lambda value: value > 0, (slow(num) for num in numbers))
)
print(results)

print("\nDouble List Comprehension")
results = [value for num in numbers for value in [slow(num)] if value > 0]
print(results)

print("\nList Comprehension with Walrus Operator")
results = [value for num in numbers if (value := slow(num)) > 0]
print(results)
39 changes: 39 additions & 0 deletions python-walrus-operator/walrus_quiz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import random
import string

QUESTIONS = {
"What is the formal name of PEP 572?": [
"Assignment Expressions",
"Named Expressions",
"The Walrus Operator",
"The Colon Equals Operator",
],
"Which one of these is an invalid use of the walrus operator?": [
"[y**2 for x in range(10) if y := f(x) > 0]",
"print(y := f(x))",
"(y := f(x))",
"any((y := f(x)) for x in range(10))",
],
}

num_correct = 0
for question, answers in QUESTIONS.items():
correct = answers[0]
random.shuffle(answers)

coded_answers = dict(zip(string.ascii_lowercase, answers))
valid_answers = sorted(coded_answers.keys())

for code, answer in coded_answers.items():
print(f" {code}) {answer}")

while (user_answer := input(f"\n{question} ")) not in valid_answers:
print(f"Please answer one of {', '.join(valid_answers)}")

if coded_answers[user_answer] == correct:
print(f"Correct, the answer is {user_answer!r}\n")
num_correct += 1
else:
print(f"No, the answer is {correct!r}\n")

print(f"You got {num_correct} correct out of {len(QUESTIONS)} questions")
42 changes: 42 additions & 0 deletions python-walrus-operator/wc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import pathlib
import sys


def count_words_1(filenames):
for filename in filenames:
path = pathlib.Path(filename)
counts = (
path.read_text().count("\n"), # Number of lines
len(path.read_text().split()), # Number of words
len(path.read_text()), # Number of characters
)
print(*counts, path)


def count_words_2(filenames):
for filename in filenames:
path = pathlib.Path(filename)
counts = (
(text := path.read_text()).count("\n"), # Number of lines
len(text.split()), # Number of words
len(text), # Number of characters
)
print(*counts, path)


def count_words_3(filenames):
for filename in filenames:
path = pathlib.Path(filename)
text = path.read_text()
counts = (
text.count("\n"), # Number of lines
len(text.split()), # Number of words
len(text), # Number of characters
)
print(*counts, path)


if __name__ == "__main__":
count_words_1(sys.argv[1:])
count_words_2(sys.argv[1:])
count_words_3(sys.argv[1:])

0 comments on commit cd9119b

Please sign in to comment.