0

Why using print won´t work, and it does work using return?

I want to output the bigger number:

def bigger(x,y):
    if x<y:
        return y
    return x

print bigger(2,7)

It prints out:

7

def bigger(x,y):
    if x<y:
        print y
    print x

print bigger(2,7)

It prints out:

7

None

Rosamunda
  • 14,620
  • 10
  • 40
  • 70

4 Answers4

4

Why using print won´t work, and it does work using return?

It works. If a function doesn't have a return statement, the function returns a None. In second case you just print it.

awesoon
  • 32,469
  • 11
  • 74
  • 99
3

Any particular reason you're not using Python's builtin max?

Functions implicitly return None if no explicit return value is specified. So, in your second example, you are printing the result of a function that doesn't return anything. While the function itself is already printing what the result is.

Your first version is the correct and what should be used version.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
3

Here is a demo of what you are seeing in the first case:

>>> def f1(): return 7
...
>>> print f1()
7

Here is a demo of what you are seeing in the second case:

>>> def f2(): pass
... 
>>> print f2()
None

And if you are looking to make the first function you have more concise, use this form:

>>> def bigger(x,y):
...    return x if x>y else y
... 
>>> print bigger(2,7)
7

Or just use the builin max (as stated in the comments) which has the advantage of returning the max of a sequence:

>>> max([1,2,3,4,5,6,7])
7
>>> max('abcdefg')
'g'

Or doing something like the max element of a data element, like the second integer of a tuple:

>>> max([(100,2),(50,7)], key=lambda x: x[1])
(50, 7)
dawg
  • 98,345
  • 23
  • 131
  • 206
2

In the first case you return the value from a function and then print it - so you have one output. In the second case you print the value inside the function and then you try to print an output from a function which doesn't return anything - so it prints the value first and then prints an empty return.

Dropout
  • 13,653
  • 10
  • 56
  • 109