-4

I am getting confused with the output of this function:

def doPrint():
    print "Hello",
    return "World"
    print "Goodbye",
    return "World"

print doPrint()

The output is "Hello World". So, can someone explain why it didn't print out "Goodbye World"?

Ashok
  • 1
  • 1
  • 2

2 Answers2

1

Everything after the first return statement is unreachable:

def doPrint():
    print "Hello",
    return "World" <- function ends here
    print "Goodbye", <- code is unreachable
    return "World"   <- code is unreachable

If you wanted both output use one return at the end:

def doPrint():
    print "Hello",
    print  "World"
    print "Goodbye",
    return "World"

In [13]: print doPrint()
Hello World
Goodbye World
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

The function only prints out "Hello ".

Then it returns, and its return value is "World.". Returning means the function is finished and the interpreter continues wherever it was before the function was called, so whatever comes after the return is irrelevant.

You called it as print doPrint(), which calls the function and prints whatever the return value is (we know it turned out to be "World.").

So the end result is that "Hello World." was printed.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79