繁体   English   中英

在函数中打印返回值

[英]Printing return value in function

我的total功能中的print(result)没有打印我的结果。

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()

我正在使用 Python-3.6.1。

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

调整您的总函数并将求和返回的值分配给变量,在这种情况下,为了更清楚地了解sums函数范围内定义的变量result的差异,请response 将其分配给变量后,您可以使用该变量打印它。

def total(firstAge,secondAge):
    response = sums(firstAge,secondAge)
    print(response)

你不需要额外的变量响应,你可以简单地做:

打印(总计(第一个年龄,第二个年龄))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM