-3

I would like to learn how to print only the return value of a function.

I.E.

def dude():
  print("Hello")
  return 1

I would like to print only the return value and not the all of the functions process. I would like to use the function and be able to use a different command to get just the values of return,without suppresing print.As print(dude()) prints Hello and the return value.

TeachMeEverything
  • 138
  • 1
  • 1
  • 13
  • 6
    You can delete `print("Hello")` line.. – jpp Mar 19 '18 at 17:38
  • Looks like it's really a case of wanting proper logging: https://stackoverflow.com/questions/6918493/in-python-why-use-logging-instead-of-print – Flexo Mar 20 '18 at 09:03

2 Answers2

1

Decorate your dude!

def dude_is_decorated(f):
  def wrap(*args, **kwargs):
    import os
    import sys
    nothing = open(os.devnull, 'w')
    sys.stdout = nothing
    sys.stderr = nothing # remove if you want your exceptions to print
    output = f()
    nothing.close()
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    return output
  return wrap

@dude_is_decorated
def dude():
  print("Hello")
  return 1

print(dude())

output:

1

TTT
  • 1,952
  • 18
  • 33
-4

This seems to work better:

def dude(x,y):
    z= x+y:
    print ("Hello")
    return z

    print(str(dude(2,3))[1:len(str(dude(2,3)))-1])

While it is ugly, It works and does not break anything else and I can make it a function. It can output just the values , it would just need more work for separating values to be used by another bit of code. It is still ugly and I was hoping for a simple solution like print(dude(2,3).return) that would be clean. I find this very useful for more complex mathematical calculations I have made. With a tiny bit of work I made this a function that automatically outputs single and multiple values. the premise remained the same , str(dude()) was the easy solution.

TeachMeEverything
  • 138
  • 1
  • 1
  • 13