Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions python-return-statement/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# The Python return Statement: Usage and Best Practices

This folder provides the code examples for the Real Python tutorial [The Python return Statement: Usage and Best Practices](https://realpython.com/python-return-statement/).

## Setup

The examples use only Python's standard library. You need Python 3.6 or later, and no extra packages.

## Usage

Run any script from your command line, for example:

```sh
$ python adding.py
$ python describe.py
```

Each script prints the results that the tutorial shows in its REPL sessions.
6 changes: 6 additions & 0 deletions python-return-statement/adding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def add(a, b):
result = a + b
return result


print(add(2, 2))
13 changes: 13 additions & 0 deletions python-return-statement/boolean_returns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def is_divisible(a, b):
return not a % b


def both_true(a, b):
return bool(a and b)


print(is_divisible(4, 2))
print(is_divisible(7, 4))

print(both_true(1, 2))
print(both_true(1, 0))
14 changes: 14 additions & 0 deletions python-return-statement/closures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def by_factor(factor):
def multiply(number):
return factor * number

return multiply


double = by_factor(2)
print(double(3))
print(double(4))

triple = by_factor(3)
print(triple(3))
print(triple(4))
19 changes: 19 additions & 0 deletions python-return-statement/describe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import statistics as st


def describe(sample):
return st.mean(sample), st.median(sample), st.mode(sample)


sample = [10, 2, 4, 7, 9, 3, 9, 8, 6, 7]
mean, median, mode = describe(sample)
print(mean)
print(median)
print(mode)

desc = describe(sample)
print(desc)
print(type(desc))

print(divmod(15, 3))
print(divmod(8, 3))
28 changes: 28 additions & 0 deletions python-return-statement/describe_namedtuple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import statistics as st
from collections import namedtuple

Desc = namedtuple("Desc", ["mean", "median", "mode"])


def describe(sample):
return Desc(
st.mean(sample),
st.median(sample),
st.mode(sample),
)


sample = [10, 2, 4, 7, 9, 3, 9, 8, 6, 7]
stat_desc = describe(sample)
print(stat_desc)

# Get the mean by its attribute name
print(stat_desc.mean)

# Get the median by its index
print(stat_desc[1])

# Unpack the values into three variables
mean, median, mode = describe(sample)
print(mean)
print(mode)
18 changes: 18 additions & 0 deletions python-return-statement/explicit_return.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def return_42():
return 42 # An explicit return statement


def get_even(numbers):
return [num for num in numbers if not num % 2]


def mean(sample):
return sum(sample) / len(sample)


num = return_42()
print(num)
print(return_42() * 2)
print(return_42() + 5)
print(get_even([1, 2, 3, 4, 5, 6]))
print(mean([1, 2, 3, 4]))
13 changes: 13 additions & 0 deletions python-return-statement/generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def gen():
yield 1
yield 2
return 3


g = gen()
print(next(g))
print(next(g))
try:
next(g)
except StopIteration as error:
print(f"StopIteration: {error.value}")
22 changes: 22 additions & 0 deletions python-return-statement/globals_vs_return.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
counter = 0


def increment_global():
global counter
counter += 1


def increment(var):
return var + 1


increment_global()
print(counter)

counter = 0
print(increment(counter))
print(counter)

# Explicitly assign a new value to counter
counter = increment(counter)
print(counter)
10 changes: 10 additions & 0 deletions python-return-statement/implicit_return.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def add_one(x):
# No return statement at all
result = x + 1 # noqa: F841


value = add_one(5)
print(value)

return_value = print("Hello, World")
print(return_value)
9 changes: 9 additions & 0 deletions python-return-statement/my_abs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def my_abs(number):
if number < 0:
return -number
return number


print(my_abs(0))
print(my_abs(-15))
print(my_abs(15))
18 changes: 18 additions & 0 deletions python-return-statement/returning_none.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def omit_return_stmt():
# Omit the return statement
pass


def bare_return():
# Use a bare return
return


def return_none_explicitly():
# Return None explicitly
return None


print(omit_return_stmt())
print(bare_return())
print(return_none_explicitly())
10 changes: 10 additions & 0 deletions python-return-statement/returning_vs_printing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def print_greeting():
print("Hello, World")


def return_greeting():
return "Hello, World"


print_greeting()
print(repr(return_greeting()))
22 changes: 22 additions & 0 deletions python-return-statement/shape_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Circle:
def __init__(self, radius):
self.radius = radius


class Square:
def __init__(self, side):
self.side = side


def shape_factory(shape_name, *args, **kwargs):
shapes = {"circle": Circle, "square": Square}
return shapes[shape_name](*args, **kwargs)


circle = shape_factory("circle", radius=20)
print(type(circle))
print(circle.radius)

square = shape_factory("square", side=10)
print(type(square))
print(square.side)
19 changes: 19 additions & 0 deletions python-return-statement/short_circuit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
def my_any(iterable):
for item in iterable:
if item:
# Short-circuit
return True
return False


def no_dead_code(condition):
if condition:
return 42
print("Hello, World")


print(my_any([0, 0, 1, 0, 0]))
print(my_any([0, 0, 0, 0, 0]))

print(no_dead_code(True))
no_dead_code(False)
21 changes: 21 additions & 0 deletions python-return-statement/timer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import time


def my_timer(func):
def _timer(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"Execution time: {end - start}")
return result

return _timer


@my_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]))
11 changes: 11 additions & 0 deletions python-return-statement/try_finally.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def func(value):
try:
return float(value)
except ValueError:
return str(value)
finally:
print("Run this before returning")


print(repr(func(9)))
print(repr(func("one")))
8 changes: 8 additions & 0 deletions python-return-statement/variance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def variance(data, ddof=0):
n = len(data)
mean = sum(data) / n
total_square_dev = sum((x - mean) ** 2 for x in data)
return total_square_dev / (n - ddof)


print(variance([3, 4, 7, 5, 6, 2, 9, 4, 1, 3]))
Loading