![](/img/trans.png)
[英]printing the function is producing output but call it is not (python)
[英]Function in python not producing output?
每当我输入以下代码时:
def in_fridge():
try:
count =fridge [wanted_food]
except KeyError:
count =0
return count
fridge ={"apples":10, "oranges":3, "milk":9}
wanted_food="apples"
in_fridge()
进入IDLE,输出“ 10”。
当我在代码编辑器中输入相同的代码,然后按F5时,将不会输出任何内容。 作为测试,我在代码编辑器中创建了一个新文件,输入:
print ("Hello World")
并忠实地获得了输出结果,即Hello World从IDLE shell显示在新窗口中。
因此,当我输入完全相同的代码时,为什么我会在IDLE环境中而不是在代码编辑器中显示一个值,我很好奇:
您已调用in_fridge
但尚未对结果进行任何处理。 您可以打印它,例如:
result = in_fridge()
print(result)
您必须打印出来,因为在IDLE中,如果未将返回值存储在变量中,则返回值将显示在控制台上。 运行脚本时不会发生这种情况,在脚本中,如果某个函数返回某些内容,则需要捕获该脚本。 使用类似于result_of_func = function_name()
=
运算符,然后打印存储在该变量中的值print(result_of_func)
这将起作用:
def in_fridge():
try:
count =fridge [wanted_food]
except KeyError:
count =0
return count
fridge ={"apples":10, "oranges":3, "milk":9}
wanted_food="apples"
print (in_fridge())
要么 :
in_fridge_count = in_fridge()
print ('Count in fridge is : ',in_fridge_count)
您不是要对in_fridge
调用的结果进行in_fridge
,应该打印它:
def in_fridge():
try:
count =fridge [wanted_food]
except KeyError:
count =0
return count
fridge ={"apples":10, "oranges":3, "milk":9}
wanted_food="apples"
print(in_fridge())
为了显示输出,您需要打印它:
print(in_fridge())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.