Skip to content
Merged
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
3 changes: 3 additions & 0 deletions python-function/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Defining Your Own Python Function

This folder provides the code examples for the Real Python tutorial [Defining Your Own Python Function](https://realpython.com/defining-your-own-python-function/).
20 changes: 20 additions & 0 deletions python-function/average.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def cumulative_average(numbers):
total = 0
for items, number in enumerate(numbers, 1):
total += number
yield total / items


values = [5, 3, 8, 2, 5] # Simulates a large data set

for cum_average in cumulative_average(values):
print(f"Cumulative average: {cum_average:.2f}")


def average(*args):
return sum(args) / len(args)


print(average(1, 2, 3, 4, 5, 6))
print(average(1, 2, 3, 4, 5, 6, 7))
print(average(1, 2, 3, 4, 5, 6, 7, 8))
17 changes: 17 additions & 0 deletions python-function/calculate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def calculate(x, y, *, operator):
if operator == "+":
return x + y
elif operator == "-":
return x - y
elif operator == "*":
return x * y
elif operator == "/":
return x / y
else:
raise ValueError("invalid operator")


calculate(3, 4, operator="+")
calculate(3, 4, operator="-")
calculate(3, 4, operator="*")
calculate(3, 4, operator="/")
2 changes: 2 additions & 0 deletions python-function/calculations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def add(a: int | float, b: int | float) -> int | float:
return a + b
11 changes: 11 additions & 0 deletions python-function/closure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def function():
value = 42

def closure():
print(f"The value is: {value}!")

return closure


reveal_number = function()
reveal_number()
5 changes: 5 additions & 0 deletions python-function/cost.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def calculate_cost(item, quantity, price):
print(f"{quantity} {item} cost ${quantity * price:.2f}")


print(calculate_cost("bananas", 6, 0.74))
7 changes: 7 additions & 0 deletions python-function/double.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def double(numbers):
for i, _ in enumerate(numbers):
numbers[i] *= 2


numbers = [1, 2, 3, 4, 5]
print(double(numbers))
10 changes: 10 additions & 0 deletions python-function/format_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def format_name(first_name, last_name, /, title=None):
full_name = f"{first_name} {last_name}"
if title is not None:
full_name = f"{title} {full_name}"
return full_name


print(format_name("Jane", "Doe"))
print(format_name("John", "Doe", title="Dr."))
print(format_name("Linda", "Brown", "PhD."))
13 changes: 13 additions & 0 deletions python-function/greeting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# def greet(name):
# print(f"Hello, {name}!")


def greet(name, verbose=False):
if verbose:
print(f"Hello, {name}! Welcome to Real Python!")
else:
print(f"Hello, {name}!")


greet("Pythonista", verbose=True)
greet("Pythonista")
2 changes: 2 additions & 0 deletions python-function/hypotenuse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def hypotenuse(a, b, /):
return (a**2 + b**2) ** 0.5
7 changes: 7 additions & 0 deletions python-function/mutable_argument.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def add_product(item, inventory=[]):
inventory.append(item)
return inventory


print(add_product("apple"))
print(add_product("banana"))
16 changes: 16 additions & 0 deletions python-function/network.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import asyncio


async def fetch_data():
print("Fetching data from the server...")
await asyncio.sleep(1) # Simulate network delay
print("Data received!")
return {"user": "john", "status": "active"}


async def main():
data = await fetch_data()
print(f"Received data: {data}")


asyncio.run(main())
14 changes: 14 additions & 0 deletions python-function/power.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def generate_power(exponent):
def power(base):
return base**exponent

return power


square = generate_power(2)
print(square(4))
print(square(6))

cube = generate_power(3)
print(cube(3))
print(cube(5))
15 changes: 15 additions & 0 deletions python-function/reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from pathlib import Path


def read_file_contents(file_path):
path = Path(file_path)

if not path.exists():
print(f"Error: The file '{file_path}' does not exist.")
return

if not path.is_file():
print(f"Error: '{file_path}' is not a file.")
return

return path.read_text(encoding="utf-8")
12 changes: 12 additions & 0 deletions python-function/report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def report(**kwargs):
print("Report:")
for key, value in kwargs.items():
print(f" - {key.capitalize()}: {value}")


report(
name="Keyboard",
price=19.99,
quantity=5,
category="PC Components",
)
6 changes: 6 additions & 0 deletions python-function/sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def sum_numbers(*numbers, precision=2):
return round(sum(numbers), precision)


print(sum_numbers(1.3467, 2.5243, precision=3))
print(sum_numbers(1.3467, 2.5243, 3))
30 changes: 30 additions & 0 deletions python-function/unpacking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# def function(x, y, z):
# print(f"{x = }")
# print(f"{y = }")
# print(f"{z = }")


# numbers = [1, 2, 3]

# function(*numbers)


# def function(one, two, three):
# print(f"{one = }")
# print(f"{two = }")
# print(f"{three = }")


# numbers = {"one": 1, "two": 2, "three": 3}
# function(**numbers)


def function(**kwargs):
for key, value in kwargs.items():
print(key, "->", value)


numbers = {"one": 1, "two": 2, "three": 3}
letters = {"a": "A", "b": "B", "c": "C"}

function(**numbers, **letters)
15 changes: 15 additions & 0 deletions python-function/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
def find_user(username, user_list):
for user in user_list:
if user["username"] == username:
return user
return None


users = [
{"username": "alice", "email": "[email protected]"},
{"username": "bob", "email": "[email protected]"},
]

find_user("alice", users)

print(find_user("linda", users))