How to Write and Use Functions in Python 3

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

How to Write and Use Functions in Python 3

Master creating reusable functions to boost code efficiency and improve programming skills

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.

Writing Your First Function

Here’s the simplest possible function example:

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

hello_function()  # Output: hello function!

Adding Parameters

You can also pass information into a function through parameters:

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

say_hello('Bob')  # Output: hello Bob

Solving Repetitive Code with Functions

Let’s solve a common problem: checking multiple word lists for color names. Instead of repeating the same logic, we can create a reusable 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 use it with any list
wordlist1 = ('red', 'car', 'kite', 'blue', 'yellow')
wordlist2 = ('balloon', 'car', 'truck', 'green', 'house')

detect_colors(wordlist1)
detect_colors(wordlist2)

Benefit: This refactored version is shorter, easier to read, and much easier to modify. If you want to check for additional colors, you only need to update the function once.

Returning Values from Functions

Functions can return values that you can use elsewhere in your program. Let’s modify our color detection function to return True or False:

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')
wordlist2 = ('car', 'kite', 'house', 'mouse')

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

# Use in conditional logic
if detect_colors(wordlist1):
    print("So Colorful!")

Returning Different Data Types

Functions can return any data type—numbers, strings, lists, or even other functions. Here are some examples:

# Returning numbers
def add_numbers(x, y):
    return x + y

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

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

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

# Returning lists
def get_colors():
    return ['red', 'green', 'blue', 'yellow']

colors = get_colors()
print(colors)  # Output: ['red', 'green', 'blue', 'yellow']

Key Takeaways

  • Functions reduce repetition: Write code once, use it multiple times
  • Functions improve readability: Break complex logic into manageable pieces
  • Functions enable reusability: Share code between different parts of your program
  • Functions can take parameters: Make your functions flexible with input values
  • Functions can return values: Send results back to be used elsewhere

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 InventiveHQ, we combine industry expertise with innovative practices to enhance your cybersecurity, streamline your IT operations, and leverage cloud technologies for optimal efficiency and growth.