Defining functions¶
In this tutorial, you will learn how to define and call functions in Python using the def keyword.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Basic familiarity with Python syntax (variables, strings, numbers)
Learning objectives¶
By the end of this tutorial, you will be able to:
- Define a function using the
defkeyword - Use parameters and return values
- Set default argument values
- Call functions with positional and keyword arguments
What is a function?¶
A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you can define it once as a function and call it whenever you need it.
Functions help you:
- Avoid repeating code
- Break complex problems into smaller, manageable pieces
- Make your code easier to read and maintain
Your first function¶
Let's start by defining a simple function that returns a greeting. In Python, you define a function using the def keyword, followed by the function name, parentheses, and a colon:
def greet():
return "Hello, World!"
message = greet()
print(message)
When you run the cell above, you should see Hello, World! printed. Here is what happened:
def greet():defined a function calledgreetreturn "Hello, World!"specified the value the function gives back when calledgreet()called the function, and the returned value was stored inmessage
Adding parameters¶
Functions become much more useful when they accept parameters — values you pass in when calling the function. Let's modify our greeting function to accept a name:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
print(greet("Bob"))
Now the function accepts a name parameter and uses it in the greeting. Each time you call the function with a different name, you get a different result.
The value you pass when calling the function ("Alice", "Bob") is called an argument. The variable in the function definition (name) is called a parameter.
Multiple parameters¶
Functions can accept more than one parameter. Separate them with commas:
def add(a, b):
return a + b
result = add(3, 5)
print(result)
The add function takes two parameters, a and b, and returns their sum.
Default arguments¶
You can give parameters default values. If the caller does not provide a value for that parameter, the default is used:
def greet_with_title(name, title="Ms"):
return f"Hello, {title} {name}!"
print(greet_with_title("Smith"))
print(greet_with_title("Jones", "Dr"))
In the first call, we did not provide a title, so the default "Ms" was used. In the second call, we provided "Dr", which overrode the default.
Parameters with default values must come after parameters without defaults in the function definition.
Keyword arguments¶
When calling a function, you can specify arguments by name. This makes your code clearer, especially when a function has several parameters:
def describe_pet(name, animal_type="dog", age=1):
return f"{name} is a {animal_type} who is {age} years old."
print(describe_pet("Rex"))
print(describe_pet("Whiskers", animal_type="cat", age=5))
print(describe_pet("Polly", age=30, animal_type="parrot"))
Notice that when using keyword arguments, the order does not matter. This makes function calls easier to read and understand.
Functions without a return value¶
Not every function needs to return a value. A function without a return statement (or with a bare return) returns None:
def say_hello(name):
print(f"Hello, {name}!")
result = say_hello("World")
print(f"Return value: {result}")
The function say_hello prints a greeting but does not return anything useful. The return value is None.
Exercise: write your own function¶
Now it is your turn! Write a function called calculate_area that takes two parameters, width and height, and returns the area of a rectangle.
Then call your function with a few different values to check that it works.
# Write your function here
# Test it
# print(calculate_area(5, 3)) # Expected: 15
# print(calculate_area(10, 2)) # Expected: 20
Solution¶
Here is one way to write the function:
def calculate_area(width, height):
return width * height
print(calculate_area(5, 3))
print(calculate_area(10, 2))
Summary¶
In this tutorial, you learned how to:
- Define a function using the
defkeyword - Accept parameters to make functions flexible
- Return values using the
returnstatement - Set default argument values for optional parameters
- Use keyword arguments for clearer function calls
What is next¶
In upcoming tutorials, you will explore:
- Lambda expressions — concise one-line functions using
lambda - Type hints — adding type annotations to function signatures
- Docstrings — documenting your functions for others (and your future self)