0

I am having a question regarding return statement for a function. Does python standards say to have a return statement for a function if it does not return anything. Nothing is stopping to write or don't write return but need to know what make a good code

Below is the example code

def test():
   print("Hello")
   return

or

def test():
    print("Hello")

Which approach is more conventional in Python?

Siavas
  • 4,992
  • 2
  • 23
  • 33
Sumit
  • 1,953
  • 6
  • 32
  • 58

3 Answers3

4

According to the PEP 8 - Style Guide for Python code, consistency is key – you should explicitly return None in your function when other code paths (such as an if branch) returns anything.

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

So in your case, you should have:

def test():
    print("Hello")

Or, if you add more functionality to this function and return something, you should have:

def test(foo):
  if foo is not None:
    print("Hello")
    return foo
  return None
Siavas
  • 4,992
  • 2
  • 23
  • 33
2

If you don't return anything, by default it will return None by default, But the value is not meant to be caught. You can read it here return, return None, and no return at all?

Rupesh Goud
  • 131
  • 1
  • 9
0

return keyword is used when you return anything from your function & it return where the function call occur. Otherwise it useless to use.

Usman
  • 1,983
  • 15
  • 28