Python 在函数中打印返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45123559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing return value in function
提问by Cornel
The print(result)
in my total
function isn't printing my result.
将print(result)
在我的total
功能不打印我的结果。
Shouldn't the sums
function return the result value to the function that called it?
sums
函数不应该将结果值返回给调用它的函数吗?
This is my code:
这是我的代码:
def main():
#Get the user's age and user's best friend's age.
firstAge = int(input("Enter your age: "))
secondAge = int(input("Enter your best friend's age: "))
total(firstAge,secondAge)
def total(firstAge,secondAge):
sums(firstAge,secondAge)
print(result)
#The sum function accepts two integers arguments and returns the sum of those arguments as an integer.
def sums(num1,num2):
result = int(num1+num2)
return result
main()
I'm using Python-3.6.1.
我正在使用 Python-3.6.1。
采纳答案by Hendrik Makait
It does return the result, but you do not assign it to anything. Thus, the result variable is not defined when you try to print it and raises an error.
它确实返回结果,但您没有将其分配给任何东西。因此,当您尝试打印结果变量并引发错误时,它并未定义结果变量。
Adjust your total function and assign the value that sums returns to a variable, in this case response
for more clarity on the difference to the variable result
defined in the scope of the sums
function. Once you have assigned it to a variable, you can print it using the variable.
调整您的 total 函数并将 sums 返回的值分配给变量,在这种情况下,response
为了更清楚地了解result
与sums
函数范围内定义的变量的差异。一旦将其分配给变量,就可以使用该变量打印它。
def total(firstAge,secondAge):
response = sums(firstAge,secondAge)
print(response)
回答by goko
You don't need the extra variable response, you can simply do:
您不需要额外的可变响应,您可以简单地执行以下操作:
print( total(firstAge,secondAge) )
打印(总计(firstAge,secondAge))