What is a function?
A function is a subroutine that accepts input values (called parameters), performs a task, and returns a result to the caller. Functions help you avoid repetition, test logic in isolation, and keep programs tidy.
- Functions take inputs via parameters.
- Functions return a value using
return.
Your first function
This function adds two numbers and returns the result:
def add_numbers(num1, num2):
# This function adds two numbers and returns the result
return num1 + num2
result = add_numbers(5, 3)
print("The result is", result)
Example: sphere surface area
The surface area of a sphere is 4 × π × r². This function takes a radius and returns the area:
import math
def sphere_area(radius):
# Surface area of a sphere = 4 * pi * r^2
return 4 * math.pi * (radius ** 2)
area = sphere_area(5)
print("The sphere's surface area is", area)
Practice task: volume of a cylinder
Ask the user for a cylinder’s radius and height. Do the calculation in a function (π × r² × h) and return the value. Extension: round to 2 decimal places.
import math
def cylinder_volume(radius, height):
volume = math.pi * (radius ** 2) * height
return round(volume, 2)
# Example usage:
r = float(input("Enter the cylinder's radius: "))
h = float(input("Enter the cylinder's height: "))
print("The volume of the cylinder is", cylinder_volume(r, h))
Default & keyword parameters
Provide defaults to make parameters optional, and use keyword arguments for clarity:
def greet(name, punctuation="!"):
return "Hello, " + name + punctuation
print(greet("Alice")) # uses default "!"
print(greet(name="Bob", punctuation=" :)")) # keyword args
Tips & best practices
Remember:
- Name functions with clear verbs:
calculate_total,find_max,format_name. - Keep functions focused—do one job well and return a value.
- Avoid unnecessary global variables; pass what you need as parameters.
- Prefer returning values over printing—printing is for the user, return values are for the program.