Captn Buzz
Captn Buzz

Reputation: 329

Printing a function in Python

I'm just starting to learn Python, and I'm currently reading a book that is teaching me, and in the book a function just like the one I have made below prints the actual text that is defined in the first function, but when I run my script it says: <function two at 0x0000000002E54EA0> as the output. What am I doing wrong? Did I install the wrong Python or something? I downloaded the 3.3.0 version

Here is my code:

def one():
    print ("lol")
    print ("dood")

def two():
    print (one)
    print (one)

print (two)

Upvotes: 7

Views: 76170

Answers (5)

Michael Mior
Michael Mior

Reputation: 28752

This is not the answer you are looking for…

But in interest of completeness, suppose you did want to print the code of the function itself. This will only work if the code was executed from a file (not a REPL).

import inspect
code, line_no = inspect.getsourcelines(two)
print(''.join(code))

That said, there aren't many good reasons for doing this.

Upvotes: 23

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

The printing happens inside your function. The function itself is a sequence of code to be executed. In your case, this code is printing "lol" and "dood" to the screen. In order to execute this code, you call the function simply by typing its name:

def one():
   print("lol")
   print("dood")

def two():
   one() #simply type the function's name to execute its code
   one()

two()

Calling print on the function itself prints a the location in memory of the code that the function executes when it is called, hence your garbled output.

Upvotes: 1

poncho
poncho

Reputation: 3

you are printing the function itself, not what the function should print, maybe you wanted to print this way

def one():
    print ("lol")
    print ("dood")

def two():
    print one()
    print one()

print two()

the output would be: lol dood

Upvotes: -1

Tim
Tim

Reputation: 12174

Your functions already print text, you don't need to print the functions. Just call them (don't forget parenthesis).

def one():
    print ("lol")
    print ("dood")

def two():
    one()
    one()

two()

Upvotes: 7

Althaf Hameez
Althaf Hameez

Reputation: 1511

You call a function in the following syntax

def two():
    one()
    one()

two()

What goes inside the parenthesis is the input parameters which you would learn later in the book.

Upvotes: 1

Related Questions