Returning a print statement still shows the value


I tested the following code:

In [266]: def foo(): 
     ...:     print("yes") 

In [267]: def bar(): 
     ...:     return foo() 

In [268]: bar()                                                                                                   

In [269]: x = bar()                                                                                               

I am very puzzled about the result, it act as

In [274]: def foo(): 
     ...:     return print("yes %.1f" %12.333) 

In [275]: foo()                                                                                                   
yes 12.3

How should I understand this? much like shell script shell’s command substitution echo $(ls)

Asked By: AbstProcDo



According to your code and explanation, I think you are mistaken with shell script

In shell to return a string (for example) you can do like that

  echo "my_string"

echo $A

value of $A will be “my_string”

To do the same in python

def foo():
    return "my_string"

a = foo()

The reason we use the echo trick in shell scripts is due to the fact that return in shell can only return values between 0-255 which is not always what we want to do (as in your example or mine we want to return a string)

Please let me know if my answer is not clear enough I will improve it thanks to comments.

Answered By: Thomas Kostas

In method you can do some actions and not return anything but directly show the result such as printing or returning a result and let another part of the code to utilize it.

So, I would like to explain what your code is doing:

In [266]: def foo(): 
     ...:     print("yes") # you are printing 'yes'

In [267]: def bar(): 
     ...:     return foo()  #you are returning a foo method

In [268]: bar()    # you are not directly calling foo()                                                                                            

In [269]: x = bar()  # you are not directly calling foo() and this is equivalent to x = print('yes')                                                                                             

Just a simple example:

>>> def foo():
...     print('Yes')
>>> def boo():
...     return foo()
>>> boo()
>>> x = boo() 
>>> x = print('Yes')
>>> x = 'Yes' # it is not printed

So, basically, a shell is not echoing any variable unless it is used in print()
However, if your method returns a value it will be printed. Basically in shell return will also play the printing roll.

>>> def noo():
...     return 'Yes'
>>> noo()
Answered By: Rarblack
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.