How to write functions in Python

Lorin Helfenstein
2 min readJun 23, 2021

--

What’s a function? In Python, a function is a group of related statements that perform a specific task.

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

Main components of a function

  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Example of a Function

def greet(name):
"""
This function greets
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

How do I call upon a function that I have written?

To call a function we simply type the function name with appropriate parameters.

In this function, if you pass the name “Lorin” in the name parameter the function would return “Hello Lorin. Good morning!”

>>> greet('Lorin')
Hello, Lorin. Good morning!

The number of arguments is important!

If a function expects two arguments you must pass in two arguments. You will get an error if you only put in one argument.

Return Function example

def absolute_value(num):
"""This function returns the absolute
value of the entered number"""

if num >= 0:
return num
else:
return -num


print(absolute_value(2))

print(absolute_value(-4))

Output

2
4

Functions are super helpful when writing code and easy to use once you understand how they work!

--

--