Functions in Python provide functionality that you or someone else has already programmed. In this post, we’ll teach you how to write your own Python functions.
Functions have a name, such as len, and the parameters are listed in parentheses after the function name. There are also functions without parameters. While len() would be an invalid call, print() is allowed: A new line is created. Many functions, however, accept one or even several parameters. With len ("Hello"), we pass the string value "Hello" as a parameter, and then the len function calculates the number of characters. The result is the number 5, which we can, for example, output directly with print(len("Hello")), or we can store it in a variable with x =len("Hello").
Now let’s focus on an example and wrap a word-counting functionality into a function so we can call it from anywhere.
Create a Python function that takes a text as input and counts the number of words in the text.
Here is a simple example of a Python function that counts the number of words in a given text:
def count_words(text):
words = text.split()
return len(words
# Example
sentence = "This is a short example sentence."
print(count_words(sentence)) # Output: 6
When you ask ChatGPT to create a function, it usually provides an example right away that shows how to call the function. The actual definition of the function starts with def, then the function is given a name (here, count_words), followed by the parameters in parentheses, which the function accepts. Essentially, these are variables that we can access within the function. So, def count_words(text) means that we must later call the count_wordsfunction with exactly one parameter, for example, like this: x = count_words("Hey you"). Within the function, we can then access the value of this parameter via the variable text. It is "Hey you".
After the line that begins with def, the indented code represents what ultimately happens when the function is called. In our case, the text passed to it is split into its words using text.split(). This gives us a list of words. len(words) calculates the number of words in the list, and the return statement returns that value. Now, if someone calls x = count_words("Hey you"), our function returns the value 2 because the text passed to it consists of two words. So, x is then 2.
Much later in this book, you’ll occasionally see lambda functions. ChatGPT, in particular, likes to generate them because they’re so nice and compact. Essentially, lambda functions are a way of writing functions that don’t contain multiline program logic—meaning no loops and no if statements—but rather a single expression that describes how a calculation is performed. We could write the preceding count_words function as a lambda function as follows and then call it as usual with count_words("Hey you"):
count_words = lambda text: len(text.split())
The word lambda is followed by the function parameters, then a colon, and finally what would otherwise come after the return statement in the function. For now, though, let’s stick to regular functions that we define using def.
Functions are always useful when the program code would otherwise become too cluttered. For example, you can put more complex calculations and tasks into a function. In your actual program code, you then simply call the functions. Especially if you need to call the same function in multiple places, it makes much more sense to put the corresponding code into a function rather than repeating the same code multiple times using copy and paste. It also makes sense to reuse functions that you’ve already programmed in other programs. Functions are self-contained code blocks that stand on their own. Variables you use within a function don’t conflict with variables of the same name in your main program or with variables from other functions. They are only valid within the function. Everything you want to access within the function is passed to it as a parameter. Everything the function is supposed to produce is returned using return:
def add(x, y):
result = x + y
return result
z = add(5, 3)
print(z) # This prints 8.
print(result) # Error!
The variable result doesn’t exist in the main part of the program at all, only in the function! That’s why an error occurs. The variable was created in the function, and when Python exits the function, it no longer exists.
You may recall that when calling the print function, you can pass the parameters sep and end: print(last_name, first_name, sep=", ", end="") prints the last name and first name, inserts a comma and a space between them instead of just a space, and doesn’t insert a line break at the end. You can also use such named parameters when calling your functions:
print(add(y=3, x=5))
This example isn’t particularly useful, nor does the order of the numbers to be added make any difference. But it’s meant to show that instead of add(5, 3), you can also call the function this way if you know the parameter names. This allows you to specify the parameters in a different order than they were defined.
Optional parameters are perhaps even more practical: When creating a function, you can assign a default value to parameters. Then these parameters are optional, and you don’t have to specify them when calling the function. If you omit optional parameters, they are assigned their default value:
def add(x, y=1): # y is an optional parameter.
return x + y
print(add(5, 3)) # 5+3 = 8
print(add(5)) # 5+1 = 6
Extend the count_words function with an optional parameter min_len, which specifies that only words of at least that length should be counted.
Here’s how you can extend the function:
def count_words(text, min_len=1):
words = text.split()
filtered = [word for word in words if len(word) >= min_len]
return len(filtered)
sentence = "This is a short sentence."
print(count_words(sentence)) # Output: 5
print(count_words(sentence, min_len=5)) # Output: 2 ("short",
# "sentence.")
Here, the name of the second parameter, min_len=5, was specified when calling the function because count_words(sentence, min_len=5) is simply much clearer than count_words(sentence, 5). However, the latter would also work and do the same thing. If you omit the second parameter, every word is counted regardless of its length because the default value for min_len is 1.
You might be wondering about that strange line with the square brackets, the for, and the if. That’s a list comprehension. It allows you to write concise expressions that, with a little practice, are easier to grasp and read, thereby contributing to more “Pythonic” code. The code line does the following: Based on the entries in the words list, a new filtered list is created that contains all words that have a certain minimum length. The code line thus filters the entries in the list according to a filter criterion.
Writing your own functions in Python gives you a way to name a piece of logic once and call it from anywhere. A good rule of thumb: the moment you catch yourself copying a block of code into a second spot, that block belongs in a function. Once def, parameters, and return feel natural, optional and named parameters will make your functions much more pleasant to call, and ChatGPT is happy to sketch a first version for you when you get stuck.
Editor’s note: This post has been adapted from a section of the book Python for AI and Data Analysis: The Practical Guide for Business and Science by Johannes Schildgen. Prof. Dr. Schildgen is a professor of databases, specializing in big data, at Ostbayerische Technische Hochschule (OTH) Regensburg (the Regensburg University of Applied Sciences). For nearly a decade, he has taught Python programming to students. As a keynote speaker, he regularly delivers engaging talks on digitalization, artificial intelligence, and other IT-driven future trends.
This post was originally published 9/2026.