Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a function in Python

Tags:

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)
like image 703
Captn Buzz Avatar asked Jan 15 '13 01:01

Captn Buzz


3 Answers

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.

like image 148
Michael Mior Avatar answered Oct 22 '22 09:10

Michael Mior


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()
like image 30
Tim Avatar answered Oct 22 '22 10:10

Tim


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.

like image 1
Althaf Hameez Avatar answered Oct 22 '22 09:10

Althaf Hameez