+ 8
Just to, uhh, advice you to, uhh, use the search bar... Kinda, I guess.
https://www.sololearn.com/Discuss/1142332/?ref=app
https://www.sololearn.com/Discuss/241342/?ref=app
https://www.sololearn.com/Discuss/251724/?ref=app
https://www.sololearn.com/Discuss/887943/?ref=app
https://www.sololearn.com/Discuss/1476808/?ref=app
https://www.sololearn.com/Discuss/21870/?ref=app
+ 6
Did you take the code above from the tutorial? Because I agree that it doesn't really make clear why you would want to return a value instead of just printing it from within the function.
It's true that if all you want to do is print the sum of two numbers, you can just do it like this:
def print_sum(a, b):
print(a + b)
print_sum(5, 4) # 9
However, this function doesn't allow you to do anything with the sum afterwards. The sum is lost immediately after it is printed and there's no way to access it from outside the function.
On the other hand, if you return the sum like this:
def add(a, b):
return a + b
, you can store it in a variable and use it, for example like this:
result = add(5, 4) # variable "result" holds the return value of add(5, 4)
print(result) # 9
print(2 * result) # 18
print(3 * add(2, 2)) # 12
print(add(add(5, 4), 10)) # 19
etc.
+ 4
When you pass 1,2 to the function your function is doing somthing with those numbers.. In this case its adding them together and returning the result. Your example is very basic for learning purposes but you can add more things to your function to manipulate the result.
+ 3
In this case there isn't much difference with this code:
def add(a,b):
print (a+b)
add(1,2)
You can make it the way you want it.
- 1
print outputs a string
return outputs an integer or other numeric type value