Notification texts go here Contact Us Buy Now!

Difference between returns and printing in python?

When it comes to Python, return and print serve distinct purposes in handling output.

def ret():
    return 42

def pri():
    print(42)

The return statement terminates the function's execution and passes a value back to the caller. In the example above, ret() returns the integer 42, which can be assigned to a variable or used in further computations.

answer = ret()
print(answer)  # Outputs: 42

On the other hand, print is a function that displays its arguments on the console or other output streams. It does not return any value, and its primary purpose is to communicate information to the user or aid in debugging.

pri()
print(answer)  # Outputs: None

In this example, pri() prints the integer 42 to the console, but since it doesn't return a value, assigning it to a variable like answer will result in None.

Here's a table summarizing the key differences between return and print:

Feature return print
Purpose Terminates function execution and passes a value back to the caller Displays arguments on the console or other output streams
Returns a value Yes No
Use case Passing data between functions, storing results, performing calculations Displaying information to the user, debugging

Ultimately, the choice between return and print depends on the specific requirements of your code. For returning values or performing calculations, return is the appropriate choice. For displaying information, print is the preferred method.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.