-3

I'm trying define a function that allows me to determine whether two user defined integers is less than 1000. If this is the case, the function should return the the sum total as 'Ans'. However, if the result is larger than 1000, the function returns the sum itself.

When using print() instead of return the solution works. I've tried the below but the function does not output the answer or the sum in any case. Any ideas why?

Side bar, because I'm defining Ans as having a value of 0 at the beginning, when using print(), the code does tend to output the answer and 0, but that's fine at this point.

Ans = 0
def Sum(Num1, Num2):
# Function to determine whether the total of two numbers is greater than 1000
  Ans = Num1 + Num2

  if Ans < 1000:
    return Ans
  else:
    return "The sum is:", Num1, "+", Num2

Num1 = int(input("Please enter one number:"))
Num2 = int(input("Please enter a second number:"))

Sum(Num1, Num2);
print(Ans)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Rahman
  • 21
  • 4
  • Duplicate of [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – esqew May 09 '21 at 20:11
  • You never do anything with the return value of your function. – juanpa.arrivillaga May 09 '21 at 20:14
  • I see that now, in future I need to call the function to get the result of 'return', rather than simply expect the return to output the result to the user. Your comment was a little short on detail as I'm reasonably new to Python, but I appreciate you taking the time to respond and your answer did ultimately help :) – Rahman May 09 '21 at 20:38

1 Answers1

0

Try this:

def sum(num1, num2):
# Function to determine whether the total of two numbers is greater than 1000
    ans = num1 + num2

    if ans < 1000:
        return ans
    else:
        message = "The sum is : " + str(num1) + " + " + str(num2)
        return message

num1 = int(input("Please enter one number:"))
num2 = int(input("Please enter a second number:"))


print(sum(num1, num2))

Also, try not to name your variables and functions with capital letters

  • I understand now, thanks a lot for that. I wrongly expected the function simply to output the answer by using return, hence my (incorrect) interchange between print() and return. I see that instead, I can use return to present the result to the function, and then call that with print(sum(num1, num2)). Thanks again, your answer was really helpful as it allowed me to understand where I went wrong without too much explanation. – Rahman May 09 '21 at 20:35