1

I just started learning Python and I've just been messing around typing different codes for practice to learn, and I made this code:

import math
def lol():
    print (math.cos(math.pi))
    print ("I hope this works")

def print_twice(bruce):
    print bruce
    print bruce



print_twice(lol())    

When I run it, my output is:

-1.0
I hope this works
None
None

How come it isn't printing the function lol() twice?

3 Answers 3

7

Your code print_twice(lol()) is saying to execute lol() and pass it's return value into print_twice(). Since you didn't specify a return value for lol(), it returns None. So, lol() is printed once when it gets executed, and both print statements in print_twice() print passed value of None.

This is what you want:

def lol():
    print (math.cos(math.pi))
    print ("I hope this works")

def print_twice(bruce):
    bruce()
    bruce()



print_twice(lol)

Instead of passing the return value of lol(), we are now passing the function lol, which we then execute twice in print_twice().

Sign up to request clarification or add additional context in comments.

1 Comment

How could I change it so it would print twice? Instead of returning None None. Is it because the function is terminate once it is called the first time in print_twice(lol())?
2

You should note that printing is different from returning.

When you call print_twice(lol()) it will first call lol() which will print -1.0 and I hope this works and will return None, then it will continue calling print_twice(None) which will call print None twice.

2 Comments

How could I change it so it would print twice? Instead of returning None None. Is it because the function is terminate once it is called the first time in print_twice(lol())?
It will print twice, try doing print_twice('foo'), you only need to make sure that its argument is a string, in that case you could change lol so it returns something. def lol: return 'foo' then print_twice(lol()) would print 'foo' twice.
0

How you might run as expected:

def lol():
    print "lol"

def run_twice(func):
    func()
    func()

run_twice(lol)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.