The world’s leading publication for data science, AI, and ML professionals.

Defining Functions in Python

Defining Python Functions

Source
Source

In computer science, functions provide a set of instructions for performing a specific task. Functions are an important part of software programs as they are at the heart of most applications we use today. In this post, we will discuss how to define different types of functions in Python.

Let’s get started!

Defining a Simple Function

To starts, let’s define a simple function. We use the ‘def’ keyword to define functions in python. Let’s define a function that prints a quote from Thomas Pynchon’s, Gravity’s Rainbow :

def print_quote():
    print("If they can get you asking the wrong questions, they don't have to worry about the answers.")

Now, if we call our function it should display our quote:

print_quote()

If we’d like, we can have the function return the string using the return keyword:

def print_quote():
    return "If they can get you asking the wrong questions, they don't have to worry about the answers."

We can then store the function return value in a variable and print the stored values:

quote = print_quote()
print(quote)

An even cleaner way to write our function would be to store the string in a variable within the function scope and return the variable:

def print_quote():
    quote =  "If they can get you asking the wrong questions, they don't have to worry about the answers."
    return quote

Let’s store the function return value in a variable and print the stored values:

my_quote = print_quote()
print(my_quote)

Defining a Function with Input

Now, let’s discuss how to define functions with input. Let’s define a function that takes a string as input and returns the length of the string.

def quote_length(input_quote):
    return len(input_quote)

We can define a few variables storing quotes of different lengths. Let’s use a few quotes from William Gaddis’s The Recognitions:

quote_one = "The most difficult challenge to the ideal is its transformation into reality, and few ideals survive."
quote_two = "We've had the goddamn Age of Faith, we've had the goddamn Age of Reason. This is the Age of Publicity."
quote_three = "Reading Proust isn't just reading a book, it's an experience and you can't reject an experience."

Let’s call our function with each of these quotes:

quote_length(quote_one)
quote_length(quote_two)
quote_length(quote_three)

We can also perform various operations on our input string. Let’s define a function that combines our quotes into a single string. We can use the ‘join()’ method to combine a list of strings into a single string:

quote_list = [quote_one, quote_two, quote_three]
def combine_quote(string_list):
    return ''.join(string_list)

If we print our function with our ‘quote_list’ as input we get the following result:

print(combine_quote(quote_list))

We can also have multiple input values in our function. Let’s have our function take an input string that specifies the author name. In the scope of the function, let’s print the author’s name:

def combine_quote(string_list, author_name):
   print("Author: ", author_name)
   return ''.join(string_list)

Now, let’s call our function and print its return value:

print(combine_quote(quote_list, 'William Gaddis'))

Returning Multiple Values

It is also very straightforward to return multiple values in a function. Let’s define a function that takes a quote, a book title, an author name and the number of pages in the book. In our function we will create a data frame that contains columns for the quote, book titles, authors, and number of pages. The function will return the data frame and its length.

To start, let’s define a list of quotes, corresponding authors, book titles, and number of pages:

quote_list = ["If they can get you asking the wrong questions, they don't have to worry about the answers.", "The most difficult challenge to the ideal is its transformation into reality, and few ideals survive.", "The truth will set you free. But not until it is finished with you."]
book_list = ['Gravity's Rainbow', 'The Recognitions', 'Infinite Jest'] 
author_list = ["Thomas Pynchon", "William Gaddis", "David Foster Wallace"]
number_of_pages = [776, 976, 1088]

Next let’s store each list in a dictionary with its appropriate key:

df = {'quote_list':quote_list, 'book_list':book_list, 'author_list':author_list, 'number_of_pages':number_of_pages}

Now, let’s pass the dictionary into the data frame constructor from the Pandas library:

import pandas as pd 
df = pd.DataFrame({'quote_list':quote_list, 'book_list':book_list, 'author_list':author_list, 'number_of_pages':number_of_pages})

Let’s also relax the limit on the number of display columns using Pandas, and print the result:

pd.set_option('display.max_columns', None)
print(df)

Now let’s wrap this code in a function. Let’s name our function ‘get_dataframe’. Our function will return the data frame and its length:

def get_dataframe(quote, book, author, pages):
    df = pd.DataFrame({'quotes':quote,   'books':book, 'authors':author, 'pages':pages})
    return df, len(df)

Now let’s call our function with our lists and store the return values in two separate variables:

df, length = get_dataframe(quote_list, book_list, author_list, number_of_pages)
print(df)
print("Data Frame Length: ", length)

We have freedom to choose which and the number of values we return in our function. Let’s also return the pandas series corresponding to the ‘quotes’ and ‘books’ columns:

def get_dataframe(quote, book, author, pages):
    df = pd.DataFrame({'quotes':quote,   'books':book, 'authors':author, 'pages':pages})
    return df, len(df), df['books'], df['quotes']

Now, let’s call our function again:

df, length, books, quotes = get_dataframe(quote_list, book_list, author_list, number_of_pages)

And we can print books:

print(books)

And quotes:

print(quotes)

I’ll stop here but feel free to play around with the code yourself.

CONCLUSIONS

To summarize, in this post we discussed how to define functions in python. First, we showed how to define a simple function that prints a string. corresponding to a book quote. Next, we discussed how to define a function that takes input values, manipulates the input, and return a value. Finally, we showed how to define a function that returns multiple values. I hope you found this post useful/interesting. The code in this post is available on GitHub. Thank you for reading!


Related Articles