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
Release: 2025-01-01 07:16:10
Original
259 people have browsed it

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)
Copy after login

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

{'part A': 1, 'part B': 2, ...}
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template