在功能中打印返回值

Cor*_*nel 5 python return function

print(result)在我的total功能不打印我的结果.

sums函数不应该将结果值返回给调用它的函数吗?

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

我正在使用Python-3.6.1.

Hen*_*ait 7

它确实返回结果,但您不会将其分配给任何内容.因此,当您尝试打印结果变量并引发错误时,不会定义结果变量.

调整总函数并将返回值的值分配给变量,在这种情况下,response为了更清楚result地区分sums函数范围中定义的变量.将变量分配给变量后,可以使用变量进行打印.

def total(firstAge,secondAge):
    response = sums(firstAge,secondAge)
    print(response)
Run Code Online (Sandbox Code Playgroud)