-5

I don't understand the difference between return and print. I was told that you should use return in function statements but it doesn't return anything, so I've been using print in my functions. But I want to understand why return statements in my functions do not work.

def triangle_area(b, h):
    return 0.5 * b * h

triangle_area(20, 10)

I would expect this return the multiplication, but it doesn't yield anything. Please help! And when I replace the return with print, it works perfectly. Am i supposed to use print in functions?

Austin
  • 25,759
  • 4
  • 25
  • 48
kimi315
  • 3
  • 1
  • 2

7 Answers7

2

return and print are two very different instructions. Return has the purpose of storing the value that is computed by a function, value that will be used according to the programmer's wish. Print does what it says: it prints whatever you tell him to print.

Using return won't print anything, because this instruction is not built for such a purpose. Only for storing. Nothing more, nothing less. print displays something on the screen.

Bogdan Doicin
  • 2,342
  • 5
  • 25
  • 34
1

Like this:

print(triangle_area(20, 10))

Good luck to you all, bro!

Akashi
  • 11
  • 5
0

It does return the product; what it doesn't do is print it (since you didn't tell it to).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Because you are not printing the return result from the function. Please try:

print(traingle_area(20,30))
v.coder
  • 1,822
  • 2
  • 15
  • 24
0

You are not receiving the output the function is returning.

print(triangle_area(20, 10))

This will show the result.

echoaman
  • 71
  • 4
  • 15
0

Functions return a value, so you need to store them in variable.

print(triangle_area(20, 10))

waynetech
  • 731
  • 6
  • 11
0

It is returning the value, you simply are not capturing it or doing anything with it. For instance:

def triangle_area(b, h):
    return 0.5 * b * h

output = triangle_area(20, 10) # capture return value
print(output)

Or as others have suggested, just pass the result straight to the print function if that's what you're looking to do:

def triangle_area(b, h):
    return 0.5 * b * h

print(triangle_area(20, 10)) # capture return value and immediately pass to print function

Note that the output will be lost if passed straight to print(). If you want to use it later in your program, the first code block is more appropriate

Reedinationer
  • 5,661
  • 1
  • 12
  • 33