-3

As you know in python when you define a function, you should put return in code to finish function. In code like below how can I finish function:

def f(x) :
    if x == 0:
         print 'yes'
    print 'no'

print f(2)

when I run this code in the last line after printing no there will be None appeared ?

AmirAli
  • 15
  • 5
  • 5
    *"As you know in python when you define a function, you should put `return` in code to finish function."* - no, that's not accurate. – jonrsharpe Apr 16 '15 at 10:58
  • @jonrsharpe: Well, it may be accurate that some readers know that, it's just that those readers are wrong. :) – abarnert Apr 16 '15 at 11:32

4 Answers4

7

You don't need to end the function, if the interpreter hits a line that is not on the expected indentation, the function is "automatically ended". But you try to print the return value of f(2). But f does return None. So you print None. Don't print the function but only call the function: f(2).

Calling f(0) will still give you no yes because you don't stop the execution after you checked for 0. Use an else clause or use return:

def f(x) :
    if x == 0:
        print 'yes'
    else:
        print 'no'

f(2)
syntonym
  • 7,134
  • 2
  • 32
  • 45
6

It seems that the question doesn't fit your problem.

If you do

print f(2)

it prints whatever the function returns. In your case, the function returns "nothing", so it implicitly returns None - which is then printed as requested.

I see two solutions:

  1. Don't print what you don't want:

    def f(x) :
        if x == 0:
             print 'yes'
        else:
             print 'no'
    
    f(2)
    
  2. Return something useful if you want the caller to print that:

    def f(x) :
        if x == 0:
             return 'yes'
        return 'no'
    
    print f(2)
    
glglgl
  • 89,107
  • 13
  • 149
  • 217
0

Because you are printing the return of function and you are not returning any thing and it prints None You should just call it it has a internal print that prints what you want to print.

AmirAli
  • 15
  • 5
Habib Kazemi
  • 2,172
  • 1
  • 24
  • 30
-2

The beauty of Python is that it asks you to format code properly. What all requires to use proper indentation. All you need to do is:

    def f(x) :
        if x == 0:
           print 'yes'
        else:
           print 'no'
    f(3)
Volatil3
  • 14,253
  • 38
  • 134
  • 263