为什么我的函数中没有

时间:2018-02-18 03:47:04

标签: python dictionary

我的代码如下:

def hello(msg):
    return print(msg)


def hi(msg):
    t = 'this is a test time'
    return print(t + msg)


data = {0: hello, 1: hi}
for i in range(2):
    x = data.get(i)
    print(x('hello world '+str(i)))

然而输出是:

hello world 0
None
this is a test timehello world 1
None

问题是为什么我有两个None

1 个答案:

答案 0 :(得分:1)

您得到None因为print语句没有返回值,它会向控制台输出一个值。

>>> a = print("Hi")
Hi
>>> print(a)
None

如果您想要将字符串添加到一起:

def hello(msg):
    return msg

def hi(msg):
    t = 'this is a test time'
    return t + msg

data = [hello, hi]
for i, func in enumerate(data):
    print(func('hello world ' + str(i)))

如果您想随机化函数的输出,请查看random.choice函数。