What is the fundamental difference between 'print' and 'return' in programming?

Patricia Arquette
Release: 2024-11-11 08:09:02
Original
726 people have browsed it

What is the fundamental difference between

The Formal Distinction Between "print" and "return"

In programming, the functions of "print" and "return" serve distinct purposes. "Print" is used to display information on the standard output stream, while "return" terminates the execution of a function and yields a value.

Consider the following example:

def funct1(param1):
    print(param1)
    return param1
Copy after login

In this function, "print(param1)" displays the value of "param1" to the console. The "return(param1)" statement then terminates the function and returns the value of "param1" to the calling function.

"Return" differs from "print" in two crucial ways:

Output Usage:

  • "Print" displays its output directly to the standard output stream. This output cannot be used by other statements in the program.
  • "Return" yields a value that can be assigned to a variable or used as an argument to another function.

Function Termination:

  • "Print" does not terminate the execution of the function. Control continues to the next statement following "print".
  • "Return" immediately terminates the function and returns control to the calling function.

To illustrate this further, consider the following code:

def main():
    ret = funct1(5)
    other = funct1(7)

    print("ret is: %s" % ret)
    print("other is: %s" % other)
Copy after login

This code calls "funct1" twice, passing different values. The output will be:

5
7
ret is: 5
other is: 7
Copy after login

The value returned by "funct1" in the first call is assigned to the variable "ret" and printed. Similarly, the value returned in the second call is assigned to "other" and printed.

In contrast to "print," "other" can be used to store or manipulate the value returned by "funct1."

The above is the detailed content of What is the fundamental difference between 'print' and 'return' in programming?. 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