Что делает return в питоне простыми словами

от admin

7. Simple statements¶

A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:

7.1. Expression statements¶

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None ). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:

An expression statement evaluates the expression list (which may be a single expression).

In interactive mode, if the value is not None , it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None , so that procedure calls do not cause any output.)

7.2. Assignment statements¶

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

(See section Primaries for the syntax definitions for attributeref, subscription, and slicing.)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy ).

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

If the target is an identifier (name):

If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.

Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal , respectively.

The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.

If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, TypeError is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError ).

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The left-hand side target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:

This description does not necessarily apply to descriptor attributes, such as properties created with property() .

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).

If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

For user-defined objects, the __setitem__() method is called with appropriate arguments.

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.

CPython implementation detail: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2] :

The specification for the *target feature.

7.2.1. Augmented assignment statements¶

Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:

(See section Primaries for the syntax definitions of the last three symbols.)

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i] , then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i] .

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.

For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments.

7.2.2. Annotated assignment statements¶

Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement:

The difference from normal Assignment statements is that only a single target is allowed.

For simple names as assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.

For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored.

If a name is annotated in a function scope, then this name is local for that scope. Annotations are never evaluated and stored in function scopes.

If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). If the right hand side is not present for an expression target, then the interpreter evaluates the target except for the last __setitem__() or __setattr__() call.

PEP 526 — Syntax for Variable Annotations

The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.

The proposal that added the typing module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs.

Changed in version 3.8: Now annotated assignments allow the same expressions in the right hand side as regular assignments. Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error.

7.3. The assert statement¶

Assert statements are a convenient way to insert debugging assertions into a program:

The simple form, assert expression , is equivalent to

The extended form, assert expression1, expression2 , is equivalent to

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O ). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

7.4. The pass statement¶

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

7.5. The del statement¶

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.

Deletion of a target list recursively deletes each target, from left to right.

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).

Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block.

7.6. The return statement¶

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None ) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

7.7. The yield statement¶

A yield statement is semantically equivalent to a yield expression . The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements

are equivalent to the yield expression statements

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

For full details of yield semantics, refer to the Yield expressions section.

7.8. The raise statement¶

If no expressions are present, raise re-raises the exception that is currently being handled, which is also known as the active exception. If there isn’t currently an active exception, a RuntimeError exception is raised indicating that this is an error.

Otherwise, raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException . If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

The type of the exception is the exception instance’s class, the value is the instance itself.

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable. You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the __cause__ attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the __cause__ attribute. If the raised exception is not handled, both exceptions will be printed:

A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an except or finally clause, or a with statement, is used. The previous exception is then attached as the new exception’s __context__ attribute:

Exception chaining can be explicitly suppressed by specifying None in the from clause:

Additional information on exceptions can be found in section Exceptions , and information about handling exceptions is in section The try statement .

Changed in version 3.3: None is now permitted as Y in raise X from Y .

New in version 3.3: The __suppress_context__ attribute to suppress automatic display of the exception context.

Changed in version 3.11: If the traceback of the active exception is modified in an except clause, a subsequent raise statement re-raises the exception with the modified traceback. Previously, the exception was re-raised with the traceback it had when it was caught.

7.9. The break statement¶

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

If a for loop is terminated by break , the loop control target keeps its current value.

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

7.10. The continue statement¶

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

7.11. The import statement¶

The basic import statement (no from clause) is executed in two steps:

find a module, loading and initializing it if necessary

define a name or names in the local namespace for the scope where the import statement occurs.

When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements.

The details of the first step, finding and loading modules, are described in greater detail in the section on the import system , which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. Note that failures in this step may indicate either that the module could not be located, or that an error occurred while initializing the module, which includes execution of the module’s code.

If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways:

If the module name is followed by as , then the name following as is bound directly to the imported module.

If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module

If the module being imported is not a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. The imported module must be accessed using its full qualified name rather than directly

The from form uses a slightly more complex process:

find the module specified in the from clause, loading and initializing it if necessary;

for each of the identifiers specified in the import clauses:

check if the imported module has an attribute by that name

if not, attempt to import a submodule with that name and then check the imported module again for that attribute

if the attribute is not found, ImportError is raised.

otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

If the list of identifiers is replaced by a star ( ‘*’ ), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__ ; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ( ‘_’ ). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError .

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod . If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod . The specification for relative imports is contained in the Package Relative Imports section.

importlib.import_module() is provided to support applications that determine dynamically the modules to be loaded.

Raises an auditing event import with arguments module , filename , sys.path , sys.meta_path , sys.path_hooks .

7.11.1. Future statements¶

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard.

The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

the module docstring (if any),

blank lines, and

other future statements.

The only feature that requires using the future statement is annotations (see PEP 563).

All historical features enabled by the future statement are still recognized by Python 3. The list includes absolute_import , division , generators , generator_stop , unicode_literals , print_function , nested_scopes and with_statement . They are all redundant because they are always enabled, and only kept for backwards compatibility.

Читать:
Что значит d в сообщениях

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it.

The direct runtime semantics are the same as for any import statement: there is a standard module __future__ , described later, and it will be imported in the usual way at the time the future statement is executed.

The interesting runtime semantics depend on the specific feature enabled by the future statement.

Note that there is nothing special about the statement:

That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions.

Code compiled by calls to the built-in functions exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to compile() — see the documentation of that function for details.

A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.

The original proposal for the __future__ mechanism.

7.12. The global statement¶

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global , although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.

CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.

Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions.

7.13. The nonlocal statement¶

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.

Функция return в Python

Оператор возврата в python используется для возврата значений из функции. Мы можем использовать оператор return только в функции. Его нельзя использовать вне функции Python.

Функция без оператора возврата

Каждая функция в Python что-то возвращает. Если функция не имеет никакого оператора возврата, она возвращает None.

Пример return

Мы можем выполнить некоторую операцию в функции и вернуть результат вызывающей стороне с помощью оператора return.

Пример оператора Return в Python

return с выражением

У нас могут быть выражения также в операторе return. В этом случае выражение оценивается и возвращается результат.

Заявление о возврате Python с выражением

Логическое значение

Давайте посмотрим на пример, в котором мы вернем логическое значение аргумента функции. Мы будем использовать функцию bool(), чтобы получить логическое значение объекта.

Логическое значение возврата

Строка

Давайте посмотрим на пример, в котором наша функция вернет строковое представление аргумента. Мы можем использовать функцию str(), чтобы получить строковое представление объекта.

Строка возврата Python

Кортеж

Иногда нам нужно преобразовать несколько переменных в кортеж. Давайте посмотрим, как написать функцию для возврата кортежа из переменного числа аргументов.

Кортеж возврата функции Python

Функция, возвращающая другую функцию

Мы также можем вернуть функцию из оператора return. Это похоже на Currying, которое представляет собой метод перевода оценки функции, которая принимает несколько аргументов, в оценку последовательности функций, каждая из которых имеет один аргумент.

Функция возврата Python

Функция, возвращающая внешнюю функцию

Мы также можем вернуть функцию, которая определена вне функции, с помощью оператора return.

Возврат внешней функции

Возврат нескольких значений

Если вы хотите вернуть несколько значений из функции, вы можете вернуть объект кортежа, списка или словаря в соответствии с вашими требованиями.

Однако, если вам нужно вернуть огромное количество значений, то использование последовательности – это слишком большая операция по перегрузке ресурсов. В этом случае мы можем использовать yield, чтобы возвращать несколько значений одно за другим.

Возврат против доходности

Резюме

Оператор return в python используется для возврата вывода из функции. Мы узнали, что мы также можем вернуть функцию из другой функции. Кроме того, выражения оцениваются, а затем функция возвращает результат.

Что делает return в Python?

Функция print() записывает, то есть «печатает», строку или число на консоли. Оператор return не выводит значение, которое возвращается при вызове функции. Это, однако, приводит к немедленному завершению или завершению функции, даже если это не последний оператор функции.

Во многих других языках функция, которая не возвращает значение, называется процедурой.

В данном коде значение, возвращаемое (то есть 2) при вызове функции foo(), используется в функции bar(). Эти возвращаемые значения печатаются на консоли только тогда, когда используются операторы печати, как показано ниже.

Пример

Вывод

Мы видим, что когда foo() вызывается из bar(), 2 не записывается в консоль. Вместо этого он используется для вычисления значения, возвращаемого из bar().

Пример оператора return Python

Давайте посмотрим на простой пример сложения двух чисел и возврата суммы вызывающему абоненту.

Мы можем оптимизировать функцию, указав выражение в операторе возврата.

Каждая функция что-то возвращает

Давайте посмотрим, что возвращается, когда функция не имеет оператора возврата.

функция Return возвращает None

Что произойдет, если в операторе ничего нет?

Когда оператор return не имеет значения, функция возвращает None.

Может иметь несколько операторов

Функция может возвращать несколько типов значений

В отличие от других языков программирования, функции Python не ограничиваются возвратом значений одного типа. Если вы посмотрите на определение функции, в нем нет никакой информации о том, что она может вернуть.

Давайте посмотрим на пример, в котором функция возвращает несколько типов значений.

Возврат нескольких значений в одном операторе

Мы можем вернуть несколько значений из одного оператора возврата. Эти значения разделяются запятой и возвращаются вызывающей программе в виде кортежа.

Python Возвращает Несколько Значений

С блоком finally

Как работает оператор return внутри блока try-except? Сначала выполняется код блока finally перед возвратом значения вызывающей стороне.

Если в блоке finally есть оператор return, то предыдущий оператор return игнорируется и возвращается значение из блока finally.

What is the purpose of the return statement? How is it different from printing?

What does the return statement do? How should it be used in Python?

How does return differ from print ?

See also

Often, people try to use print in a loop inside a function in order to see multiple values, and want to be able to use the results from outside. They need to be returned, but return exits the function the first time. See How can I use `return` to get back multiple values from a loop? Can I put them in a list?.

Often, beginners will write a function that ultimately print s something rather than return ing it, and then also try to print the result, resulting in an unexpected None . See Why is "None" printed after my function's output?.

Occasionally in 3.x, people try to assign the result of print to a name, or use it in another expression, like input(print(‘prompt:’)) . In 3.x, print is a function, so this is not a syntax error, but it returns None rather than what was displayed. See Why does the print function return None?.

Occasionally, people write code that tries to print the result from a recursive call, rather than return ing it properly. Just as if the function were merely called, this does not work to propagate the value back through the recursion. See Why does my recursive function return None?.

Consider How do I get a result (output) from a function? How can I use the result later? for questions that are simply about how to use return , without considering print .

wjandrea's user avatar

15 Answers 15

The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

For example, here’s a function utilizing both print() and return :

Now you can run code that calls foo, like so:

If you run this as a script (e.g. a .py file) as opposed to in the Python interpreter, you will get the following output:

I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.

Here’s another example from the interpreter that demonstrates that:

You can see that when foo() is called from bar() , 1 isn’t written to the console. Instead it is used to calculate the value returned from bar() .

print() is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement. return causes the function to stop executing and hand a value back to whatever called it.

wjandrea's user avatar

Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can’t be used by another function.

I’ll attempt to explain this better with some examples, and a couple definitions from Wikipedia.

Here is the definition of a function from Wikipedia

A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..

Think about that for a second. What does it mean when you say the function has a value?

What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)

Why would you want that you ask?

What about other functions that may accept the same type of value as an input?

There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.

Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program

It might be a bit hard to grasp what this means if you’re just new to programming, but I think you will get it after some experimentation. In general though, you can do things like print in a function, and you can also have a return statement at the end.

Just remember that when you use return you are basically saying «A call to this function is the same as writing the value that gets returned»

Python will actually insert a return value for you if you decline to put in your own, it’s called «None», and it’s a special type that simply means nothing, or null.

I think the dictionary is your best reference here

return gives something back or replies to the caller of the function while print produces text

In python, we start defining a function with def , and generally — but not necessarily — end the function with return .

Suppose we want a function that adds 2 to the input value x . In mathematics, we might write something like f(x) = x + 2 , describing that relationship: the value of the function, evaluated at x , is equal to x + 2 .

In Python, it looks like this instead:

That is: we def ine a function named f , which will be given an x value. When the code runs we figure out x + 2 , and return that value. Instead of describing a relationship, we lay out steps that must be taken to calculate the result.

After defining the function, it can be called with whatever argument you like. It doesn’t have to be named x in the calling code, and it doesn’t even have to be a variable:

We could write the code for the function in some other ways. For example:

Again, we are following steps in order — x = x + 2 changes what x refers to (now it means the result from the sum), and that is what gets return ed by return x (because that’s the value *at the time that the return happens).

Sheikh Ahmad Shah's user avatar

return means "output this value from this function".

print means "send this value to (generally) stdout"

In the Python REPL, a function’s return value will be output to the screen by default (this isn’t the same as print ing it). This output only happens at the REPL, not when running code from a .py file. It is the same as the output from any other expression at the REPL.

This is an example of print:

This is an example of return:

This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.

In line number 4:

After the conditional statement gets executed the ret() function gets terminated due to return temp (line 4). Thus the print(«return statement») does not get executed.

This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.

Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.

To bring out the difference between print and return:

Akaisteph7's user avatar

Note that return can also be used for control flow. By putting one or more return statements in the middle of a function, we can say: "stop executing this function. We’ve either got what we wanted or something’s gone wrong!"

For example, imagine trying to implement str.find(sub) if we only had str.index(sub) available ( index raises a ValueError if the substring isn’t found, whereas find returns -1 ).

We could use a try/except block:

This is fine, and it works, but it’s not very expressive. It’s not immediately clear what would cause str.index to raise a ValueError : a reader of this code must understand the workings of str.index in order to understand the logic of find .

Rather than add a doc-string, saying ". unless sub isn’t found, in which case return -1 ", we could make the code document itself, like this:

This makes the logic very clear.

The other nice thing about this is that once we get to return s.index(sub) we don’t need to wrap it in a try/except because we already know that the substring is present!

See the Code Style section of the Python Guide for more advice on this way of using return .

LondonRob's user avatar

To put it as simply as possible:

return makes the value (a variable, often) available for use by the caller (for example, to be stored by a function that the function using return is within). Without return , your value or variable wouldn’t be available for the caller to store/re-use.

print , by contrast, prints to the screen — but does not make the value or variable available for use by the caller.

Andrew's user avatar

Difference between «return» and «print» can also be found in the following example:

The above code will give correct results for all inputs.

NOTE: This will fail for many test cases.

FAILURE : Test case input: 3, 8.

FAILURE : Test case input: 4, 3.

FAILURE : Test case input: 3, 3.

You passed 0 out of 3 test cases

Ashwini Chaudhary's user avatar

Here is my understanding. (hope it will help someone and it’s correct).

So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return — we want the value (count + 1) to replace 0. If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change. I hope I got it right. Oh, and return is always inside a function.

return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.

print should be used when you want to display a meaningful and desired output to the user and you don’t want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.

The following code shows how to use return and print properly:

This explanation is true for all of the programming languages not just python.

Habib Karbasian's user avatar

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def .

icarito's user avatar

Best thing about return function is you can return a value from function but you can do same with print so whats the difference ? Basically return not about just returning it gives output in object form so that we can save that return value from function to any variable but we can’t do with print because its same like stdout/cout in C Programming .

Follow below code for better understanding

We are now doing our own math functions for add, subtract, multiply, and divide . The important thing to notice is the last line where we say return a + b (in add ). What this does is the following:

  1. Our function is called with two arguments: a and b .
  2. We print out what our function is doing, in this case "ADDING."
  3. Then we tell Python to do something kind of backward: we return the addition of a + b . You might say this as, "I add a and b then return them."
  4. Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.

Vrushal Raut's user avatar

The simple truth is that print and return have nothing to do with each other. print is used to display things in the terminal (for command-line programs). 1 return is used to get a result back when you call a function, so that you can use it in the next step of the program’s logic.

Many beginners are confused when they try out code at Python’s interpreter prompt 2 , like

The value was displayed; doesn’t this mean that return displays things? No. If you try the same code in a .py file, you can see for yourself that running the script doesn’t cause the 1 to display.

This shouldn’t actually be confusing, because it works the same way as any other expression:

This displays at the interactive prompt, but not if we make a script that just says 1 + 1 and try running it.

Again: if you need something to display as part of your script, print it. If you need to use it in the next step of the calculation, return it.

The secret is that the interactive prompt is causing the result to be displayed, not the code. It’s a separate step that the prompt does for you, so that you can see how the code works a step at a time, for testing purposes.

Now, let’s see what happens with print :

The result will display, whether we have this in an interactive prompt or in a script. print is explicitly used to display the value — and as we can see, it displays differently. The interactive prompt uses what is called the repr of the value that was returned from example , while print uses the str of the value.

In practical terms: print shows us what the value looks like, in text form (for a string, that just means the contents of the string as-is). The interactive prompt shows us what the value is — typically, by writing something that looks like the source code we would use to create it. 3

But wait — print is a function, right? (In 3.x, anyway). So it returned a value, right? Isn’t the interpreter prompt supposed to display that in its separate step? What happened?

There is one more trick: print returns the special value None , which the interpreter prompt will ignore. We can test this by using some expressions that evaluate to None:

In each case, there is no separate line at all for output, not even a blank line — the interpreter prompt just goes back to the prompt.

1 It can also be used to write into files, although this is a less common idea and normally it will be clearer to use the .write method.

2 This is sometimes called the REPL, which stands for "read-eval-print loop".

3 This isn’t always practical, or even possible — especially once we start defining our own classes. The firm rule is that repr will lean on the .__repr__ method of the object to do the dirty work; similarly, str leans on .__str__ .

Похожие статьи