SwadhyAI Notes

All Python notes

Python Functions 🔧

Reusable Code

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

🍳 Analogy: The Recipe

Think of a function as a recipe.
- Parameters are the ingredients list (what you need).
- Arguments are the actual ingredients you use (eggs, flour).
- The Return Value is the finished cake!
You can use the same recipe (function) to bake many different cakes (calls) just by changing the ingredients (arguments).

✨ Creating and Calling

python
def my_function():
  print("Hello from a function")

my_function() # Call the function

🎯 Real-World Application: Helper Functions

Functions are used to break down complex tasks into smaller, reusable pieces.

python
def calculate_tax(price, tax_rate=0.05):
    return price * tax_rate

total_price = 100
tax = calculate_tax(total_price)
print(f"Tax: ${tax}")

📥 Arguments and Parameters

Information can be passed into functions as arguments.

python
def greet(name):
  print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

🌟 Arbitrary Arguments (*args)

If you do not know how many arguments that will be passed into your function, add a * before the parameter name. The function will receive a tuple of arguments.

python
def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

🔑 Arbitrary Keyword Arguments (**kwargs)

If you do not know how many keyword arguments that will be passed into your function, add two asterisks: ** before the parameter name. The function will receive a dictionary of arguments.

python
def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

🔙 Default Parameter Value

If we call the function without argument, it uses the default value:

python
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function() # Uses default "Norway"

✨ Pro Tip: Docstrings

Always document your functions using docstrings so others (and you) know what they do!

python
def add(x, y):
    """
    This function adds two numbers.
    """
    return x + y

✨ Pro Tip: Type Hinting

Modern Python (3.5+) supports type hinting to indicate the expected type of arguments and return values. This doesn't enforce types but helps with readability and IDE support.

python
def add(x: int, y: int) -> int:
    return x + y

💡 Recursion

Python accepts function recursion, which means a defined function can call itself. This is useful for mathematical problems like factorial or Fibonacci.

python
def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result)
  else:
    result = 0
  return result

print("

Recursion Example Results")
tri_recursion(6)

λ Lambda Functions

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

python
# Syntax: lambda arguments : expression
x = lambda a : a + 10
print(x(5)) # 15

# Multiply argument a with argument b
x = lambda a, b : a * b
print(x(5, 6)) # 30

The power of lambda is better shown when you use them as an anonymous function inside another function.

python
def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11)) # 22
print(mytripler(11)) # 33