[英]Printing return value in function
The print(result)
in my total
function isn't printing my result.我的total
功能中的print(result)
没有打印我的结果。
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。
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.调整您的总函数并将求和返回的值分配给变量,在这种情况下,为了更清楚地了解sums
函数范围内定义的变量result
的差异,请response
。 Once you have assigned it to a variable, you can print it using the variable.将其分配给变量后,您可以使用该变量打印它。
def total(firstAge,secondAge):
response = sums(firstAge,secondAge)
print(response)
You don't need the extra variable response, you can simply do:你不需要额外的变量响应,你可以简单地做:
print( total(firstAge,secondAge) )打印(总计(第一个年龄,第二个年龄))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.