6/13/2023 0 Comments Python functionIf we want to return multiple pieces of information, therefore, we will need to come up with a single object (in Python, "value" and "object" are effectively synonyms this doesn't work out so well for some other languages.) return terminates the function - again, we just determined the result of the calculation, so there is no reason to calculate any further. The function can only return once each time it is called. (Again: we are returning a value, not a variable.) 2 We can return the value directly: simply return 'hello world', without assigning to x. We can use the value directly to call another function: for example, print(foo()). The calling code doesn't have to know anything about how the function is written, or what names it uses for things. After that, result is our own, local name for that string, and we can do whatever we want with it. Just as we may say result = 'hello ' + 'world', we may say result = foo(). The other key point here is that a call to a function is an expression, so we can use it the same way that we use, say, the result of an addition. We need to write the calling code to use the return value: result = example() (That's presumably why you got a NameError.)Īfter we use return in the function: def example(): So return x does not enable the calling code to use x after calling the function, and does not modify any existing value that x had in the context of the call. The main trick here is that return returns a value, not a variable. Broadly speaking, the purpose of a function is to compute a value, and return signifies "this is the value we computed we are done here". The natural, simple, direct, explicit way to get information back from a function is to return it. The direct way is to return a value from the function, as you tried, and let the calling code use that value. Effectively, there are two ways: directly and indirectly.
0 Comments
Leave a Reply. |