def square(x):
"""Returns the square of a number."""
return x ** 2
print(square(4)) # Output: 16
16
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
# 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!
# 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)
# 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
# an function without names
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
8
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
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()