Python Defining Functions
Table of Contents
In the last lesson, we learned the purpose of functions in Introduction to Functions. Now let’s define and call our own function.
Let’s Write Our Own Function
In the last article, we learned what functions are and why they are useful. Now let’s learn how to actually define one.
Defining a function is like writing a recipe. We write down the steps once. Give it a name. Then whenever we want to follow those steps, we just call the name.
In Python, we define a function using the def keyword. It is short for “define.” Let’s see how it works.
The Basic Structure of a Python Function
def function_name(): # code goes hereThat is the skeleton. Let me break it down.
def— this keyword tells Python we are defining a function.function_name— we choose this name. Make it descriptive.()— parentheses. They hold any inputs the function needs. For now, empty.:— colon. It marks the start of the function body.- Then the indented code. This is what runs when the function is called.
That’s it. That’s the whole syntax.
A Simple Python Function
Let’s define a function that prints a greeting.
def say_hello(): print("Hello there!")
say_hello()Output
Hello there!Let me explain what happened.
- We defined the function
say_hello. It doesn’t take any inputs. It just prints a message. - Then we called it with
say_hello(). The parentheses at the end are important. They tell Python to run the function. - Python runs the code inside. It prints the message.
We can call it as many times as we want. Each time, it runs the same code.
Naming Rules for Python Functions
Function names follow the same rules as variable names.
- They can contain letters, numbers, and underscores.
- They cannot start with a number.
- They cannot be a keyword.
- They are case-sensitive.
And the convention is to use snake_case (all lowercase, with underscores between words).
Good names: calculate_area, print_message, get_user_input.
Bad names: CalculateArea, 1st_function, for.
Python Functions with Parameters
Most functions need some input to work with. Those inputs are called parameters. We put them inside the parentheses when defining the function.
def greet(name): print(f"Hello, {name}!")
greet("Alex")greet("Sam")Output
Hello, Alex!Hello, Sam!Here, name is a parameter. When we call greet("Alex"), the value "Alex" is passed in. Inside the function, name becomes "Alex". So it prints the right greeting.
We can have multiple parameters, separated by commas.
def introduce(name, age): print(f"My name is {name} and I am {age} years old.")
introduce("Alex", 25)Output
My name is Alex and I am 25 years old.That’s how we pass multiple pieces of information.
Calling a Function in Python
To call a function, we write its name followed by parentheses. If it needs arguments, we put them inside the parentheses.
say_hello() # no argumentsgreet("Alex") # one argumentintroduce("Sam", 30) # two argumentsThe number of arguments we pass must match the number of parameters the function expects. If we pass too few or too many, Python will give us an error.
def add(a, b): print(a + b)
add(5) # Error! Missing one argumentadd(5, 3, 2) # Error! Too many argumentsSo let’s be careful to match them.
A Function with a Return Value
We will cover return values in a later article. But just so we know, functions can also give something back instead of printing. That is done with the return keyword. For now, we are focusing on printing functions.
Empty Functions in Python
Sometimes we want to define a function but we are not ready to write the code yet. We can use pass as a placeholder.
def my_function(): passThis defines a function that does nothing. Later, we can come back and fill in the details. Without pass, Python would give an error because the function body is empty.
Docstrings in Python Functions
It is a good habit to add a short description at the top of our function. This is called a docstring. It is just a string literal, usually triple-quoted, that explains what the function does.
def greet(name): """Print a greeting with the given name.""" print(f"Hello, {name}!")The docstring is not required. But it makes our code easier to understand. And many tools can read docstrings to generate documentation automatically.
A Complete Python Function Example
Let’s put it all together. Here is a small program with a few functions.
def say_hello(): print("Hello!")
def greet(name): print(f"Nice to meet you, {name}.")
def add(a, b): print(f"The sum is {a + b}")
say_hello()greet("Alex")add(5, 3)Output
Hello!Nice to meet you, Alex.The sum is 8See how each function does one small thing? That is good design. It keeps our code organized and easy to read.
Common Mistakes with Python Functions
Mistake 1: Forgetting the Colon
def say_hello() print("Hello")Error! Missing colon after the parentheses.
So what do we do? We add the colon.
def say_hello(): print("Hello")Mistake 2: Forgetting the Indentation
def say_hello():print("Hello")Error! The print line needs indentation.
So what do we do? We indent the code inside the function.
def say_hello(): print("Hello")Mistake 3: Forgetting to Call the Function
def say_hello(): print("Hello")
# Nothing happens because we didn't call itSo what do we do? We call it.
say_hello()Mistake 4: Using the Wrong Number of Arguments
def add(a, b): print(a + b)
add(5)Error! Missing one argument.
So what do we do? We pass the right number of arguments.
add(5, 3)Next, we will learn about Python Function Arguments and pass information into a function.