0

My question is, is it ok to use return in python as follows:

    def do_something():
        do something
        return

I know this function doesn't return anything, but is there any use in putting return at the bottom? I normally do this out of habit, but am new to python.

Robotica
  • 75
  • 1
  • 1
  • 8

1 Answers1

0

In the example code you posted, no, it doesn't serve any special purpose. An implicit return of None will happen regardless once the end of the function is reached.

There are legitimate cases to use a return without a value though:

def func(n):
  if n >= 0:
    return

  print("N was negative!") 

func(1) #  Doesn't print anything
func(-1) # Prints that N is negative

This is a contrived example, but it will only print if n is negative since the return will cause the function to return and exit. return can be used as a control-flow mechanism to prevent the rest of the function from executing. Whether or not it should be used like this though is the source of endless debate, and depends on the use case.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117