How should I add x and y together?

Question

How should I add x and y together?

Answer

In this exercise we need to return the addition of our two parameters, x and y. We can do math in a return statement like this:

def my_function(value_1, value_2):
  return value_1 + value_2
5 Likes

How come my code does not get accepted when I use the sum() function to add them?

Depends how you use sum(), sum() is for iterable like a list. Which means you first have to convert to list, which sounds like taking extra (unnecessary) steps

2 Likes

I used the same concept like this one but instead of return , I wrote print. like:
def my_function(value_1, value_2):
print value_1 + value_2

I know this is wrong and I instantly corrected, but I observed that the output for this code was:
18
None

can you please tell me why “None” was also printed?

1 Like

None is the absence of a return value. So if you have a function which doesn’t return anything (or explicitly returns None) and you print the caller result, you will get None

3 Likes

def my_function(value_1, value_2):
return value_1 + value_2

will it also be correct if I had used print value_1 + value_2?
so print instead of return.

The exercise doesn’t mention whether we should print or return the sum, and I no longer have PRO, so I can’t test it out for myself. You can try resetting the exercise, writing the function to printer rather than return, and see if you’re allowed to pass.

However, note that we return from functions far more often than we print out something. This is because we can use that returned value and do many, many more useful things with it, whereas there is little we can do with printing.

2 Likes