Search code examples
pythonpython-3.xif-statementreturn

Return inside if condition


   def hi (n):
    if n<=5:
        print("we are inside hi")
        n+=1
        return n

n=1
hi(n)

1) In the above code i have declared a function hi() which takes an input n

2)I want to iterate inside the if condition until n is less than 5,totally execute the print statement 4 times

3)But it is not working after execution of one time inside the condition

4)I am thinking i have given return statement for if condition but the function is totally being exit

5)(i am thinking i am returning the n value to the if condition and it checks the condition and it will iterate ) if wrong correct me


Solution

  • Not sure exactly what you want to achieve, but based on the info you have provided:

    def hi (n):
        while (n < 5):
            print("we are inside hi")
            n -= 1
    

    Briefly speaking, using return inside a function means to return the value that is followed or return None if there is no value. In addition, the execution of the function is terminated just after the return statement is executed.

    You can use the return statement, but if you want to iterate it is not correct because your function will terminate its execution. Also remember that once you execute the iteration of the loop, there won't be more statements to execute inside your function which means an implicit return statement will be executed which returns None, and again function ends execution.