When to Flesh Out - Python Python - Return | Coursera Community

When to Flesh Out - Python Python - Return

  • 22 April 2021
  • 1 reply
  • 23 views

Badge +1

Hello Everyone,

I’m learning return values and statements and wanted to know if anyone knew when to flesh out the body of a function or when to have the return statement nested under the function? what is the general rule of using the return statement and value?

 

Examples:

 

def area_triangle(base, height):

    return base * height / 2

 

area_a = area_triangle (5,4)

area_b = area_triangle(7,3)

sum = area_a + area_b

print(“The sum of both areas is: “ + str(sum))

The sum of both is: 20.5

 

Then there’s

 

def convert_seconds (seconds):

    hours = seconds//3600

    minutes = (seconds - hours * 3600) // 60

    remaining_seconds = hours * 3600 - minutes * 60

     return hours, minutes, remaining_seconds

 

hours, minutes, seconds = convert_seconds(5000)

print(hours, minutes, seconds)

1 23 20

 

So, the first one has the return right up under the defined function while the second has a fleshed out body. Does anyone know when to flesh out the body of a defined function? (examples are taken from python videos).


1 reply

Here’s the functionality of seconds conversion, implemented in two different ways (and corrected, yours has a small bug):

def convert_seconds(s):
h = s // 3600
m = (s - (h * 3600)) // 60
rs = s - (h * 3600) - (m * 60)
return h, m, rs

def convert_seconds_signleline(s):
return (s // 3600), ((s - ((s // 3600) * 3600)) // 60), s - ((s // 3600) * 3600) - (((s - ((s // 3600) * 3600)) // 60) * 60)

They both work correctly, and both work exactly the same (in terms of returned values):

Code and execution results.

Which one is more readable for you? Which one would you understand effortlessly?

For “when to flesh out a body of a function?” - that’s your answer.

Reply