Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function printing in Print Function in Python

My question is for below code why None is getting print in place of function output and why function output is getting before its position.

def print_spam():
    print('spam')


def do_twice(r,ps):
    g  = ps()
    print(r,'is a',g)
    print(r,'is a',ps())

do_twice('xyz',print_spam)

Output is

spam
xyz is a None
spam
xyz is a None
like image 673
Vishal Tyagi Avatar asked Jun 12 '26 01:06

Vishal Tyagi


1 Answers

The function print_spam() does not return anything. It just prints a statement.

Change it to:

def print_spam():
    print('spam')
    return 'spam'

Because your function doesn't return anything, it defaults to None. Now when assigning the function output to g, it will contain the returned string of the function (spam).

like image 130
TerryA Avatar answered Jun 14 '26 15:06

TerryA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!