Disable Python return statement from print return object

I want to disable the "return" from printing any object that it returns to the python shell.

For example, the python script test.py example looks like this:

def func1():
    list = [1,2,3,4,5]
    print list
    return list

Now, if I do the following:

python -i test.py
>>>func1()

This always gives me two fingerprints on the python shell. I just want to print and get the returned object.

+3
source share
4 answers

The reason for printing is not the return statement, but the shell itself. The shell prints any object that is the result of an operation on the command line.

This is why this happens:

>>> a = 'hallo'
>>> a
'hallo'

The last statement has the value a as the result (since it is not assigned to anything else). Therefore, it is printed by the shell.

"", . , ( , ). , .

+10

Python . , , . ,

rv = func1()

func1()

.

+6

, , , .

, . . , -.

. , , , .

+5

If you do not want it to display a value, assign the result of the function to a variable:

H:\test>copy con test.py
def func1():
  list = [1,2,3,4,5]
  print list
  return list
^Z
        1 file(s) copied.

H:\test>python -i test.py
>>> func1()
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
>>> x = func1()  # assign result to a variable to suppress auto printout
[1, 2, 3, 4, 5]
>>>
0
source

Source: https://habr.com/ru/post/1711202/


All Articles