如何将函数附加到列表,然后打印i

2024-05-19 09:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个基本的配方查看器,我偶然发现了一个问题,当我试图打印保存的配方时,它会显示[None],正如所见,配方首先是一个函数,然后它被附加到一个列表中,然后我在加载它时尝试打印它。你知道吗

下面的代码可以解释更多。如何阻止[None, None]出现?下面的代码是我做的一个样本,我可以很容易地适应解决我的食谱中的问题,而不是张贴在这里我的整个代码。你知道吗

b = [] #this is meant to resemble my list

def function():  # this is meant to resemble my recipe
     print("hi")


function()
a = input('write 1 = ') # this is meant to resemble the user to saving the recipe

if a == '1':
    b.append(function()) # this is meant to resemble me saving the recipe onto a list


print(b) # this is meant to resemble me loading the recipe 

当我运行我的代码时,很抱歉没有足够的信誉点来发布一个图像,但这是python shell中出现的

hi
write '1' = 1 #user input
hi
[None]

Tags: theto代码noneismy配方recipe
1条回答
网友
1楼 · 发布于 2024-05-19 09:34:04

你没有从你的函数中返回任何东西。你在打印,但那不是一回事。你知道吗

使用return返回值:

def function():
     return "hi"

print()写入终端时,函数的调用者不会得到该输出。你知道吗

始终可以使用print()打印返回值:

print(function())

相关问题 更多 >

    热门问题