How to Write and Use Functions in Python 3 (Beginner’s Guide)

"Printing press symbolizing function creation process in Python 3 tutorial"

What Are Functions in Programming?

In programming, a function is a reusable block of code designed to perform a specific task. Think of it as a mini-program inside your larger program. You write it once, and then you can “call” it (or run it) anytime you need that task done—without rewriting the same lines of code.

Functions are known by different names depending on the language. In some, they’re called methods, especially when tied to objects or classes. But no matter the name, the concept is the same: reduce repetition, improve readability, and break your code into logical, manageable parts.

Why Functions Matter in Python

Python is built around simplicity and readability—and functions play a major role in that. They help you avoid writing repetitive code and make your logic easier to understand and maintain. Whether you’re writing a basic script or building a large application, functions allow you to:

  • Keep your code DRY (Don’t Repeat Yourself)
  • Make it easier to debug and test
  • Allow others (or future you) to reuse and understand your code

Even if you’re just starting out, you’ve already used functions—every time you use print(), you’re calling a function. In this article, we’ll go deeper and learn how to define your own.

Built-in Functions vs. Custom Functions

Using Built-in Functions

Python comes with a large set of built-in functions that you can use without writing any additional code. These are tools the language provides by default to handle common tasks like printing output, working with numbers, or manipulating data. You’ve probably used functions like print(), len(), input(), and type() already.

For example:

print("Hello, world!")  # Calls the built-in print() function

This line of code uses print() to display text in your console. Behind the scenes, this function is written in C, the language Python itself is built on.

Creating Your Own Functions

While built-in functions are powerful, they can’t solve every problem specific to your application. That’s where custom functions come in. You can define your own functions to group related logic into a single, reusable block.

Custom functions allow you to:

  • Simplify complex operations
  • Avoid repeating the same logic multiple times
  • Write cleaner, more maintainable code

In this article, you’ll learn how to create custom functions to streamline your code and solve real problems efficiently—starting with a basic example, then improving a repetitive script using functions.

Understanding the Problem: Repetitive Code

Let’s walk through a common beginner mistake—writing the same logic over and over again.

Imagine you have three lists of words, and you want to check each one for color names like “red,” “blue,” “green,” and “yellow.” You might start with something like this:

wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'balloon','car','truck','blue','green','house','horn'
wordlist3 = 'red','car','water','blue','fire','house','mouse'

for word in wordlist1:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')

# and then repeat that whole block for wordlist2 and wordlist3...

Why This Is a Problem

  • Repetition: The same set of if statements is repeated three times.
  • Hard to maintain: If you want to add a new color (say “pink”), you have to modify every loop.
  • Scales poorly: More word lists mean more repetitive code.

A Better Way

Instead of repeating your logic, you can write it once in a function, and call it whenever you need it. That’s what we’ll do in the next section.

Writing Your First Function

Now that we’ve seen how repetitive code can get out of hand, let’s explore how functions solve this problem.

What Is a Function?

A function is a reusable block of code that performs a specific task. Instead of copying and pasting logic multiple times, you can define it once and call it as needed.

Here’s the simplest possible example:

def hello_function():
print('hello function!')

hello_function()

Adding Input

You can also pass information into a function through parameters:

def say_hello(name):
print("hello " + name)

say_hello('Bob') # Output: hello Bob

Applying It to Our Word List Problem

Let’s rewrite the repetitive color-checking logic using a function:

def detect_colors(wordlist):
for word in wordlist:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')

Now you can simply call detect_colors() with any list:

wordlist1 = ('red', 'car', 'kite', 'blue', 'yellow', 'house', 'mouse')
detect_colors(wordlist1)

In the next section, we’ll apply this function to multiple lists and see how much cleaner the code becomes.

Refactoring Repetitive Code with Functions

Let’s return to our original problem. We had multiple word lists and repeated the same block of for loops and if statements for each list. That approach was inefficient and hard to maintain.

Original (Repetitive) Code

wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'balloon','car','truck','blue','green','house','horn'
wordlist3 = 'red','car','water','blue','fire','house','mouse'

for word in wordlist1:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
# ... repeated again for wordlist2 and wordlist3 ...

This resulted in a long, bloated script. If we wanted to add a new color like “pink”, we’d have to add a new if condition in every loop — a tedious and error-prone task.

Refactored Code Using a Function

With our detect_colors() function, we can now simplify this dramatically:

def detect_colors(wordlist):
for word in wordlist:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')

wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'balloon','car','truck','blue','green','house','horn'
wordlist3 = 'red','car','water','blue','fire','house','mouse'

detect_colors(wordlist1)
detect_colors(wordlist2)
detect_colors(wordlist3)

This refactored version is shorter, easier to read, and much easier to modify. If we ever want to check for additional colors, we only need to update the detect_colors() function once. Every place the function is called will benefit from the update automatically.

In the next section, we’ll explore how functions can return values, enabling even more flexibility in how your code behaves.

Returning Values from Functions

Up to this point, we’ve used functions to print results directly to the screen. But what if you want to store or use the result somewhere else in your program instead of just displaying it? That’s where return values come in.

Using return Instead of print

Let’s modify our detect_colors() function so it returns True if any of the specified colors are found and False if none are found:

def detect_colors(wordlist):
foundcolor = False
for word in wordlist:
if word == 'red':
foundcolor = True
if word == 'green':
foundcolor = True
if word == 'blue':
foundcolor = True
if word == 'yellow':
foundcolor = True
return foundcolor

wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'car','kite','house','mouse'

print(detect_colors(wordlist1)) # Outputs: True
print(detect_colors(wordlist2)) # Outputs: False

Using the Return Value in Other Logic

Now that our function returns a value, we can plug it into other parts of our program, such as an if statement:

if detect_colors(wordlist1):
print("So Colorful!")

This approach makes your code more modular and more powerful. You can now reuse the return value however you like—storing it in variables, comparing it, or even passing it into other functions.

In the next section, we’ll explore how functions can return different types of values, like strings and numbers—to build even more flexible and reusable logic.

Returning Other Types of Data

Functions aren’t limited to returning just True or False. In Python, functions can return any data type—strings, numbers, lists, or even other functions. This allows you to build more flexible and powerful applications.

Returning Numbers

Let’s look at a simple example of a function that returns the sum of two numbers:

def add_numbers(x, y):
return x + y

print(add_numbers(6, 7)) # Outputs: 13

Here, the function calculates a value and hands it back to the caller using the return statement. We then print the result or use it in further calculations.

Returning Strings

You can also return strings or any other object. For instance:

def select_greeting(index):
greetings = ['hello', 'howdy', 'hey there!']
return greetings[index]

print(select_greeting(2)) # Outputs: hey there!

The function select_greeting() returns one of the strings from the list based on the index provided.

Why This Matters

Using return makes your functions more versatile. Instead of being limited to a single action (like printing), they can become building blocks that send results back to be used elsewhere in your program. Whether you’re building a calculator, a chatbot, or a web application, return values are how your logic passes information between parts of your code.

In the next section, we’ll wrap up with a quick summary and how you can keep building your knowledge of Python functions.

Summary

Functions are one of the most important tools in any programmer’s toolkit. In this article, you learned:

  • What functions are and why they matter
  • How to create your own functions in Python
  • How to simplify repetitive code using functions
  • How to pass arguments into a function
  • How to return values from a function, including booleans, strings, and numbers

By using functions, your code becomes easier to read, easier to maintain, and much more powerful. Instead of copying and pasting the same logic, you can define it once and reuse it whenever you need it.

Now that you understand the basics, try writing a few of your own functions! Refactor some old code. Solve small problems using reusable logic. And when you’re ready, explore more advanced topics like default arguments, keyword arguments, and lambda functions.

Elevate Your IT Efficiency with Expert Solutions

Transform Your Technology, Propel Your Business

Unlock advanced technology solutions tailored to your business needs. At Inventive HQ, we combine industry expertise with innovative practices to enhance your cybersecurity, streamline your IT operations, and leverage cloud technologies for optimal efficiency and growth.