Def return print python

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 .

This is an important reference question, but there are many related questions that might be a better target for closing duplicates. Sorry about the length of the «see-also» section, but this time it really seems necessary.

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 :

def foo(): print("hello from inside of foo") return 1 

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

if __name__ == '__main__': print("going to call foo") x = foo() print("called foo") print("foo returned " + str(x)) 

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:

going to call foo hello from inside foo called foo foo returned 1 

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

Читайте также:  Linux обновить python до последней версии

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

>>> def foo(): . print("hello within foo") . return 1 . >>> foo() hello within foo 1 >>> def bar(): . return 10 * foo() . >>> bar() hello within foo 10 

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.

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?

def square(n): return n * n def add_one(n): return n + 1 print square(12) # square(12) is the same as writing 144 print add_one(square(12)) print add_one(144) #These both have the same output 

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.

Источник

чем отличается return от print() в python [закрыт]

Закрыт. Этот вопрос необходимо уточнить или дополнить подробностями. Ответы на него в данный момент не принимаются.

Хотите улучшить этот вопрос? Добавьте больше подробностей и уточните проблему, отредактировав это сообщение.

Читайте также:  Opencart php notice undefined index token in

return Это возврат значения из фукнции, print Это вывод на экран. Они отличаются примерно как картошка и кастрюля.

2 ответа 2

Возвращает значение из функции.Пример:

return значит что функция что-то возвращает. Это что-то можно потом передавать в другую функцию, или иным образом взаимодействовать. print просто что-то печатает, при этом функция будет возвращать None . В дальнейшем вы с этим значением никак работать не сможете. Также после выполнения инструкции return дальнейший код функции не читается, она всегда заканчивается return

def foo(x): return x**2 print(x + 1) # эта строка кода "не достижима", питон ее даже читать не будет def bar(x): print(x**2) # тут можно еще сколько угодно принтов и прочего кода написать print(foo(3) * 2) # 18 print(bar(3) * 2) # ошибка 

Похожие

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.27.43548

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

python — difference between print and return [duplicate]

It prints one hundred track names. If I swap print for return track[‘name’] , it prints only one track name. why?

Because return returns from the function. Execution of the function stops immediately and resumes with whatever called the function.

In fact, it does not even print a single track name. The return prints nothing. It could be that your calling code prints the return value (which is the first track name that the function found).

The function isn’t printing anything, it’s just returning the first item in the list. If you are calling this in the python command wheel, the shell prints the return value.

4 Answers 4

Return stops execution of a whole function and gives the value back to the callee (hence the name return). Because you call it in a for loop, it executes on the first iteration, meaning it runs once then stops execution. Take this as an example:

def test(): for x in range(1, 5): print(x) return x test() 

This will give the following output:

This is because the for loop starts at 1, prints 1, but then stops all execution at the return statement and returns 1, the current x.

Return is nowhere near the same as print. Print prints to output, return returns a given value to the callee. Here’s an example:

This function returns a value of a+b back to the callee:

In this case, c, when assigning, called add. The result is then returned to c, the callee, and is stored.

When you use return, the loop is ended at the first return only. That’s why only one name is returned. return is used when you want to return something from one fucntion to other.

That’s not case with print. print will keep executing till the loop ends. That’s why all track names are printed.

Читайте также:  Заголовок

Return will simply stop executing the function (whether it’s a loop, switch, or etc. )!

By using return you can assign a method that returns a value, allowing you to assign that method to a variable.

You can then assign this method to a variable, like so:

onePlusOneEquals = onePlusOne() 

Print will simply print the value to the console. So now you can print the value of onePlusOneEquals, like so:

OK. Programming Languages 101 time, kids.

In Python, the print statement does just that — print the indicated value to the standard output (STDOUT). In this case, you’re looping over the entire tracks array, and printing each value in it.

In most programming languages, the return keyword will pass the indicated value up to the calling function, where it can be placed in a variable and used for something else. For instance, if you called your function like this:

track = show_recommendations_for_track(someTrackList) 

The value of track would be the first value in someTrackList . Because return ends the function immediately, only the first value in the array would be placed in track , and the rest of the loop would not occur.

Источник

Return and print in functions

If I type x(2) it will output on the console: 1 2 right?
Is the variable a printed a second time only when I type print x(2) ?

3 Answers 3

then the function X gets called with 2 as a parameter, let’s go inside it:

it’ll print 1 and 2, then it returns a which has the value 1.

The returned value (1) gets printed since you wrote print X(2) .

If you have wrote X(2) (without print ), you would get 1 and 2 printed, and the returned value will be unused.

Now, when x(5) is called, it will print 6 to the console. However, if you did y=x(5) , the value of y would be None .

If you called x(5) , it would still print 6 to the console. But, if you did y=x(5) , the value of y would be 6 , not None

The two appear to do similar things, but are quite different.

Most of the time, you’ll be using return as an output for a function. Using print implies just that: printing something as a string (perhaps to a file or interpretor, etc).

Also, you can’t do anything with a value printed by a function. Returning a value provides you more in this regard since it isn’t «garbage collected» like a printed value.

Return also allows you to break out of a function.

>>> def x(y): . squared = y ** 2 . return squared . >>> x(2) 4 >>> z = x(2) >>> z 4 >>> def a(b): . squared = b ** 2 . print(squared) . >>> a(2) 4 >>> c = a(2) 4 >>> c >>> 

In this example, I have two functions: x and a. Both take one positional argument and either return or print that valued squared.

Notice that if I assign the function with an argument to a variable, I can return that value by calling the variable with the function returning a value but not with a function printing the value.

Источник

Оцените статью