简体   繁体   中英

Printing return value in function

The print(result) in my total function isn't printing my result.

Shouldn't the sums function return the result value to the function that called it?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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