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.
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.
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