Tips for Writing Functions in Python and Examples¶

  1. Use Meaningful Names: Choose descriptive names that convey the function's purpose.
  2. Keep It Simple: Functions should do one thing and do it well.
  3. Document Your Functions: Use docstrings to describe what the function does.
  4. Use Default Values: Set default parameter values when applicable.
  5. Handle Exceptions: Use try-except blocks to manage errors gracefully.
  6. Use Type Hints: Specify expected data types for better readability.
  7. Use Keyword Arguments: Allow functions to accept arguments by name.

Basic Function¶

In [ ]:
def square(x):
    """Returns the square of a number."""
    return x ** 2

print(square(4))  # Output: 16
16

Function with Default Arguments¶

In [ ]:
def power(base, exponent=2):
    """Raises base to the power of exponent."""
    return base ** exponent

print(power(3))      # Output: 9 (3^2)
print(power(3, 3))   # Output: 27 (3^3)
9
27

Function with Variable-Length Arguments¶

In [ ]:
# if you don't know the numbers of input variables, you can use *args
def concatenate_strings(*args):
    """Concatenates a variable number of strings."""
    return " ".join(args)

print(concatenate_strings("Hello", "world!"))  # Output: "Hello world!"
Hello world!

Function Returning Multiple Values¶

In [ ]:
# return more than one values
def min_max(numbers):
    """Returns the minimum and maximum values from a list."""
    return min(numbers), max(numbers)

result = min_max([3, 1, 4, 1, 5, 9])
print(result)  # Output: (1, 9)
(1, 9)

Recursive Function¶

In [ ]:
# apply the function in the function itself.

def factorial(n):
    """Calculates the factorial of n."""
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120
120

Lambda Function¶

In [ ]:
# an function without names

add = lambda x, y: x + y
print(add(3, 5))  # Output: 8
8

Mean, Median, Mode¶

In [2]:
from scipy import stats
import numpy as np

# Function to calculate the mean
def calculate_mean(data):
    return np.mean(data)

# Function to calculate the mode
def calculate_mode(data):
    mode_result = stats.mode(data, keepdims=True)
    return mode_result.mode[0]

# Function to calculate the median
def calculate_median(data):
    return np.median(data)

# Example usage
data = [1, 2, 2, 3, 4, 5, 5, 5, 6]

mean_value = calculate_mean(data)
mode_value = calculate_mode(data)
median_value = calculate_median(data)

print(data)
print("Mean:", mean_value)
print("Mode:", mode_value)
print("Median:", median_value)
[1, 2, 2, 3, 4, 5, 5, 5, 6]
Mean: 3.6666666666666665
Mode: 5
Median: 4.0
In [18]:
import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(4,3))
plt.hist(data,bins= np.arange(1, 8, 1),facecolor='gray',edgecolor='black')
plt.grid(alpha=0.3)
plt.vlines(mean_value,ymin=0,ymax=3,color='r',label='mean',linewidth=2)
plt.vlines(median_value,ymin=0,ymax=3,color='b',label='median',linewidth=2)
plt.vlines(mode_value,ymin=0,ymax=3,color='g',label='mode',linewidth=2)
plt.legend()
plt.xlabel('Value')
plt.ylabel('Counts')
plt.title('Histogram')
plt.show()
In [ ]: