Page12/20
Functions & Scope Β· Page 1 of 2
Defining Functions
Functions & Scope
What is a Function?
In mathematics, a function maps inputs to outputs: f(x) = y. In programming, a function is a named, reusable block of code that accepts zero or more inputs (called parameters), executes a defined task, and optionally returns a value. Functions are the primary mechanism for abstraction and code reuse β the industry principle called DRY (Don't Repeat Yourself) says: if you write the same logic twice, it belongs in a function.
Functions also make code testable and readable: instead of a 200-line script, well-written code reads like a sequence of named steps.
Basic Syntax
def calculate_mse(actual, predicted):
n = len(actual)
error = sum((a - p)**2 for a, p in zip(actual, predicted)) / n
return error
Default & Keyword Arguments
def train_model(data, epochs=10, learning_rate=0.01):
pass
train_model(my_data) # uses defaults
train_model(my_data, epochs=50, learning_rate=0.1) # overrides
*args and **kwargs
Pass a variable number of arguments:
def log_metrics(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
log_metrics(accuracy=0.9, loss=0.05)
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦