Skip to content

Commit

Permalink
Merge branch 'master' into jinja-primer-update
Browse files Browse the repository at this point in the history
  • Loading branch information
gahjelle authored Aug 16, 2024
2 parents 6aec9f1 + 63915dd commit 3b5b13b
Show file tree
Hide file tree
Showing 10 changed files with 133 additions and 10 deletions.
2 changes: 1 addition & 1 deletion python-class/car.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def brake(self, value):
print(f"Braking to {self.speed} km/h...")

def __str__(self):
return f"{self.make}, {self.model}, {self.color}: ({self.year})"
return f"{self.make} {self.model}, {self.color} ({self.year})"

def __repr__(self):
return (
Expand Down
2 changes: 1 addition & 1 deletion python-class/circle.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ def radius(self, value):
self._radius = value

def area(self):
return round(math.pi * self._radius**2, 2)
return math.pi * self._radius**2
6 changes: 3 additions & 3 deletions python-class/mro.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
class A:
def method(self):
print("A.method")
print("A.method()")


class B(A):
def method(self):
print("B.method")
print("B.method()")


class C(A):
def method(self):
print("C.method")
print("C.method()")


class D(B, C):
Expand Down
4 changes: 2 additions & 2 deletions python-class/robot.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ def __init__(self):
self.position = 0

def move_up(self, distance=1):
self.position += 1
self.position += distance
print(f"Moving arm {distance} cm up...")

def move_down(self, distance=1):
self.position -= 1
self.position -= distance
print(f"Moving arm {distance} cm down...")

def weld(self):
Expand Down
4 changes: 2 additions & 2 deletions python-class/shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self, radius):
self.radius = radius

def area(self):
return round(math.pi * self.radius**2, 2)
return math.pi * self.radius**2


class Square:
Expand All @@ -31,4 +31,4 @@ def __init__(self, side):
self.side = side

def area(self):
return round(self.side**2, 2)
return self.side**2
2 changes: 1 addition & 1 deletion python-class/square.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ def side(self, value):
self._side = value

def calculate_area(self):
return round(self._side**2, 2)
return self._side**2
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.
31 changes: 31 additions & 0 deletions python-walrus-operator/slow_calculations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
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 3b5b13b

Please sign in to comment.