diff --git a/python-function/README.md b/python-function/README.md new file mode 100644 index 0000000000..9037ca6c2a --- /dev/null +++ b/python-function/README.md @@ -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/). diff --git a/python-function/average.py b/python-function/average.py new file mode 100644 index 0000000000..ef87ac8da7 --- /dev/null +++ b/python-function/average.py @@ -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)) diff --git a/python-function/calculate.py b/python-function/calculate.py new file mode 100644 index 0000000000..bf3f00bbe5 --- /dev/null +++ b/python-function/calculate.py @@ -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="/") diff --git a/python-function/calculations.py b/python-function/calculations.py new file mode 100644 index 0000000000..816ce7c733 --- /dev/null +++ b/python-function/calculations.py @@ -0,0 +1,2 @@ +def add(a: int | float, b: int | float) -> int | float: + return a + b diff --git a/python-function/closure.py b/python-function/closure.py new file mode 100644 index 0000000000..b96153cf21 --- /dev/null +++ b/python-function/closure.py @@ -0,0 +1,11 @@ +def function(): + value = 42 + + def closure(): + print(f"The value is: {value}!") + + return closure + + +reveal_number = function() +reveal_number() diff --git a/python-function/cost.py b/python-function/cost.py new file mode 100644 index 0000000000..4840a2d8ad --- /dev/null +++ b/python-function/cost.py @@ -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)) diff --git a/python-function/double.py b/python-function/double.py new file mode 100644 index 0000000000..f4576d165f --- /dev/null +++ b/python-function/double.py @@ -0,0 +1,7 @@ +def double(numbers): + for i, _ in enumerate(numbers): + numbers[i] *= 2 + + +numbers = [1, 2, 3, 4, 5] +print(double(numbers)) diff --git a/python-function/format_name.py b/python-function/format_name.py new file mode 100644 index 0000000000..e260549ea7 --- /dev/null +++ b/python-function/format_name.py @@ -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.")) diff --git a/python-function/greeting.py b/python-function/greeting.py new file mode 100644 index 0000000000..76870c41cb --- /dev/null +++ b/python-function/greeting.py @@ -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") diff --git a/python-function/hypotenuse.py b/python-function/hypotenuse.py new file mode 100644 index 0000000000..f9d01f738f --- /dev/null +++ b/python-function/hypotenuse.py @@ -0,0 +1,2 @@ +def hypotenuse(a, b, /): + return (a**2 + b**2) ** 0.5 diff --git a/python-function/mutable_argument.py b/python-function/mutable_argument.py new file mode 100644 index 0000000000..df0a5b91e8 --- /dev/null +++ b/python-function/mutable_argument.py @@ -0,0 +1,7 @@ +def add_product(item, inventory=[]): + inventory.append(item) + return inventory + + +print(add_product("apple")) +print(add_product("banana")) diff --git a/python-function/network.py b/python-function/network.py new file mode 100644 index 0000000000..c9156459a1 --- /dev/null +++ b/python-function/network.py @@ -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()) diff --git a/python-function/power.py b/python-function/power.py new file mode 100644 index 0000000000..8c16c54d17 --- /dev/null +++ b/python-function/power.py @@ -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)) diff --git a/python-function/reader.py b/python-function/reader.py new file mode 100644 index 0000000000..9b0a8a1227 --- /dev/null +++ b/python-function/reader.py @@ -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") diff --git a/python-function/report.py b/python-function/report.py new file mode 100644 index 0000000000..73a57e0f45 --- /dev/null +++ b/python-function/report.py @@ -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", +) diff --git a/python-function/sum.py b/python-function/sum.py new file mode 100644 index 0000000000..ecf824257f --- /dev/null +++ b/python-function/sum.py @@ -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)) diff --git a/python-function/unpacking.py b/python-function/unpacking.py new file mode 100644 index 0000000000..6da19a0a54 --- /dev/null +++ b/python-function/unpacking.py @@ -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) diff --git a/python-function/users.py b/python-function/users.py new file mode 100644 index 0000000000..e8b8c914fc --- /dev/null +++ b/python-function/users.py @@ -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": "alice@example.com"}, + {"username": "bob", "email": "bob@example.com"}, +] + +find_user("alice", users) + +print(find_user("linda", users))