Home >Backend Development >Python Tutorial >Return vs. Print in Python Functions: What's the Difference?

Return vs. Print in Python Functions: What's the Difference?

Susan Sarandon
Susan SarandonOriginal
2025-01-01 07:16:10290browse

Return vs. Print in Python Functions: What's the Difference?

Returning vs. Printing Function Output

In the context of Python functions, understanding the distinction between returning and printing output is crucial. While both actions display data, they serve different purposes and have implications for code functionality.

Printing

The print() function simply outputs the provided data to the console. It does not store data or make it available for further use. The output is temporary and vanishes once the code execution moves on.

Returning

The return statement in a function ends the function call and "returns" data back to the caller. The returned data can be assigned to a variable or used in subsequent code statements. The data returned from a function continues to exist even after the function call concludes.

Example

Consider the following autoparts() function:

def autoparts():
    parts_dict = {}
    list_of_parts = open('list_of_parts.txt', 'r')
    
    for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v

    # Print the dictionary without returning it
    print(parts_dict)

Running this function will output the contents of the parts_dict dictionary to the console:

{'part A': 1, 'part B': 2, ...}

However, the dictionary itself is not accessible outside the autoparts() function. To make it available, we need to return the dictionary using the return statement:

def autoparts():
    parts_dict = {}
    list_of_parts = open('list_of_parts.txt', 'r')
    
    for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v

    # Return the dictionary
    return parts_dict

Now, we can assign the returned dictionary to a variable in the calling code:

my_auto_parts = autoparts()
print(my_auto_parts['engine'])  # Output: Value associated with 'engine' key

By returning the dictionary, we can access and manipulate its contents even after the autoparts() function has finished executing.

The above is the detailed content of Return vs. Print in Python Functions: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn