Definition
Why write the same steps again and again when you can name them once?
A function is a named, reusable block of code that performs a task. It is defined with def, takes inputs called parameters, and can send back a result with return. Calling the function with arguments runs its code. Parameters can have default values.
In simple words
A function is like a machine: put something in, get something out. def to_fahrenheit(celsius): return celsius * 9 / 5 + 32 builds the machine. to_fahrenheit(100) uses it and gives 212.0. Write the steps once, use them anywhere.
Overview
- A function is a named, reusable block of code that performs one task.
- def name(parameters): defines it; calling name(arguments) runs it.
- Parameters are the names in the definition; arguments are the actual values passed in.
- return sends a value back to the caller; without it, a function returns None.
- Functions follow DRY (Don't Repeat Yourself): write logic once, use it many times.
- Small functions with clear names and docstrings make programs easy to test and read.
Why it matters
Functions keep programs short, readable and easy to test. Every library you will use, from print() to scikit-learn's fit(), is made of functions, and AI pipelines are chains of them.
Key terms
- Function
- A named, reusable block of code that performs one task.
- Parameter
- A name in the function definition that receives an input.
- Argument
- The actual value passed when calling a function.
- Return value
- The result a function sends back with return; None if there is no return.
- Default parameter
- A parameter with a value used when no argument is given.
- Keyword argument
- An argument passed by name, such as round(3.14159, ndigits=2).
Types
Functions can be grouped by where they come from and by the kinds of parameters they accept. These types cover almost every function you will write or call.
1. Built-in functions
Functions that come with Python and are always available, such as print(), len(), sum(), max(), sorted(), round() and type().
- How it works: They are part of the builtins module, so you call them without importing anything.
- Example: sum(marks) / len(marks) computes an average in one line.
- When to use it: Use them before writing your own: they are tested, fast and familiar to every reader.
2. User-defined functions with positional parameters
Functions you write, whose arguments are matched to parameters by position.
- How it works: The first argument goes to the first parameter, the second to the second, and so on; the count must match.
- Example: def percentage(scored, total): return scored / total * 100; percentage(72, 80) gives 90.0.
- When to use it: Use them for most tasks with a small, fixed number of inputs.
3. Default parameters
Parameters given a value in the definition, used when the caller leaves them out.
- How it works: def greet(name, language="en"): makes language optional; defaults must come after required parameters.
- Example: round(3.14159) uses 0 decimals by default; round(3.14159, 2) overrides it.
- When to use it: Use them for settings that are usually the same; never use a mutable default like [] (use None instead).
4. Keyword arguments
Arguments passed as name=value, so their order does not matter.
- How it works: Python matches each keyword to the parameter of that name; keywords make calls self-explanatory.
- Example: print("a", "b", sep="-"); train_test_split(X, y, test_size=0.2, random_state=0).
- When to use it: Use them for optional settings and whenever a call has several numbers that could be confused.
5. Variable-length parameters (*args and **kwargs)
Parameters that accept any number of positional (*args) or keyword (**kwargs) arguments.
- How it works: *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.
- Example: def average(*marks): return sum(marks) / len(marks); average(70, 80, 90) gives 80.0.
- When to use it: Use them when the number of inputs varies, or to pass settings through to another function.
6. Functions returning several values
Functions that return more than one result, packed as a tuple.
- How it works: return a, b builds a tuple; the caller unpacks it with x, y = f().
- Example: def min_max(values): return min(values), max(values); low, high = min_max(marks).
- When to use it: Use them when results naturally belong together, such as a quotient and a remainder.
Explained in detail
Why functions matter
A function packages a piece of logic under a name. Once grade(mark) exists, you can use it anywhere without thinking about how it works, test it on its own, and fix it in one place if it is wrong. This idea, called abstraction, is how large programs stay manageable. A rule many professionals follow is: if you copy and paste the same lines a second time, turn them into a function. Python's built-in tools, print(), len(), sorted(), are themselves functions that someone wrote once so that millions could reuse them.
Parameters and arguments
| Form | Definition | Call |
|---|---|---|
| Positional | def area(w, h): | area(3, 4) |
| Keyword | def area(w, h): | area(h=4, w=3) |
| Default | def greet(name, lang="en"): | greet("Riya") or greet("Riya", "hi") |
| Any number | def total(*nums): | total(1, 2, 3) |
| Named extras | def show(**info): | show(name="Riya", age=15) |
return versus print
The most common beginner confusion is between returning and printing. print() shows a value on screen and the value is then gone; return hands the value back to the code that called the function, which can store it, compare it or pass it on. A function such as def average(marks): print(sum(marks) / len(marks)) displays the answer but returns None, so best = average(marks) stores nothing useful. As a rule, functions that calculate should return, and only the top-level part of your program should print. return also ends the function immediately, which is useful for leaving early when the input is invalid.
Writing good functions
- One job per function, with a verb-like name: calculate_average, is_valid_mark.
- Keep them short; if a function needs scrolling, split it.
- Add a one-line docstring saying what it returns.
- Avoid changing global variables; take inputs as parameters and give results with return.
- Never use a list or dictionary as a default value, def f(items=[]):, because the same list is reused across calls; use None and create the list inside.
In AI code, almost everything is a function call: model.fit(X, y), train_test_split(data, test_size=0.2), tokenizer(text). Keyword arguments with defaults, like test_size=0.2, are how libraries let you change one setting without specifying dozens of others, so being comfortable with them makes library documentation much easier to read.
How it works
- Parameters are the names in the definition; arguments are the values you pass in.
- return sends a value back and ends the function. Without it, the function returns None.
- Default values make parameters optional: def greet(name, greeting="Hello").
- Keyword arguments name the parameter when calling: greet("Riya", greeting="Namaste").
In code
A converter with return, a default parameter, and a function that uses another function.
def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
def describe(celsius, unit="C"):
if celsius >= 35:
feeling = "hot"
elif celsius >= 20:
feeling = "pleasant"
else:
feeling = "cool"
return f"{celsius}{unit} is {to_fahrenheit(celsius):.1f}F and feels {feeling}"
print(to_fahrenheit(100))
for temp in [38, 25, 12]:
print(describe(temp))
def no_return():
x = 1
print("A function without return gives:", no_return())Output
212.0 38C is 100.4F and feels hot 25C is 77.0F and feels pleasant 12C is 53.6F and feels cool A function without return gives: None
Try it yourself
Put the lines in order
Build a function that returns the average of a list, then use it.
- 1 total = sum(numbers)
- 2marks = [70, 80, 90]
- 3print(average(marks))
- 4 return total / len(numbers)
- 5def average(numbers):
Common mistakes
- Printing inside the function when you meant to return the value.
- Calling a function before it is defined.
- Forgetting the brackets: average without () is the function itself, not its result.
Check yourself
Summary
- def creates a named, reusable block with parameters.
- return sends a result back; otherwise None.
- Defaults and keyword arguments make functions flexible.
Finished reading?
Sources: W3Schools: Python Functions