Skip to content

Commit

Permalink
Merge pull request #579 from realpython/syntactic-sugar-python
Browse files Browse the repository at this point in the history
Sample code for the article on syntactic sugar
  • Loading branch information
brendaweles authored Sep 20, 2024
2 parents e52d11b + ca54e62 commit fe6ef2f
Show file tree
Hide file tree
Showing 9 changed files with 146 additions and 0 deletions.
3 changes: 3 additions & 0 deletions syntactic-sugar-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Syntactic Sugar: Why Python is Sweet and Pythonic

This folder provides the code examples for the Real Python tutorial [Syntactic Sugar: Why Python is Sweet and Pythonic](https://realpython.com/python-syntactic-sugar/).
9 changes: 9 additions & 0 deletions syntactic-sugar-python/assertions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
number = 42
if __debug__:
if not number > 0:
raise AssertionError("number must be positive")

number = -42
if __debug__:
if not number > 0:
raise AssertionError("number must be positive")
21 changes: 21 additions & 0 deletions syntactic-sugar-python/balance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
debit = 300
credit = 450

print(
f"Debit: ${debit:.2f}, Credit: ${credit:.2f}, Balance: ${credit - debit:.2f}"
)

print(
"Debit: ${:.2f}, Credit: ${:.2f}, Balance: ${:.2f}".format(
debit, credit, credit - debit
)
)

print(
"Debit: $"
+ format(debit, ".2f")
+ ", Credit: $"
+ format(credit, ".2f")
+ ", Balance: $"
+ format(credit - debit, ".2f")
)
18 changes: 18 additions & 0 deletions syntactic-sugar-python/circle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from math import pi


class Circle:
def __init__(self, radius):
self.radius = radius

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

def circumference(self):
return 2 * pi * self.radius


circle = Circle(10)
print(circle.radius)
print(circle.area())
print(circle.circumference())
11 changes: 11 additions & 0 deletions syntactic-sugar-python/membership.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def is_member(value, iterable):
for current_value in iterable:
if current_value == value:
return True
return False


print(is_member(5, [1, 2, 3, 4, 5]))
print(not is_member(5, [1, 2, 3, 4, 5]))
print(is_member(100, [1, 2, 3, 4, 5]))
print(not is_member(100, [1, 2, 3, 4, 5]))
30 changes: 30 additions & 0 deletions syntactic-sugar-python/stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Stack:
def __init__(self):
self.items = []

def push(self, item):
self.items.append(item)

def pop(self):
return self.items.pop()

def __iter__(self):
yield from self.items

# def __iter__(self):
# return iter(self.items)

# def __iter__(self):
# for item in self.items:
# yield item


stack = Stack()
stack.push("one")
stack.push("two")
stack.push("three")

for item in stack:
print(item)

print(stack.pop())
23 changes: 23 additions & 0 deletions syntactic-sugar-python/timing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import functools
import time


def timer(func):
@functools.wraps(func)
def _timer(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"Execution time: {end - start:.4f} seconds")
return result

return _timer


@timer
def delayed_mean(sample):
time.sleep(1)
return sum(sample) / len(sample)


print(delayed_mean([10, 2, 4, 7, 9, 3, 9, 8, 6, 7]))
12 changes: 12 additions & 0 deletions syntactic-sugar-python/twice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Twice:
def __init__(self, items):
self.items = list(items)

def __iter__(self):
yield from self.items
print("Halfway there!")
yield from self.items


for number in Twice([1, 2, 3]):
print(f"-> {number}")
19 changes: 19 additions & 0 deletions syntactic-sugar-python/user_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# With assignment operator
while (line := input("Type some text: ")) != "stop":
print(line)


# With assignment before loop
line = input("Type some text: ")

while line != "stop":
print(line)
line = input("Type some text: ")


# With condition inside loop
while True:
line = input("Type some text: ")
if line == "stop":
break
print(line)

0 comments on commit fe6ef2f

Please sign in to comment.