Reputation: 125
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
Upvotes: 1
Views: 2063
Reputation: 370
you can use this:
def hi (n):
while n <= 5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
you need a loop to iterate and return statement will exit from the function call.
Upvotes: 0
Reputation: 69963
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.
Upvotes: 1
Reputation: 1493
Of course, you need a loop to make iteration. If you just want to print the statement 4 times, simply make a range of loop.
def hi ():
for n in range(4):
print(n+1," we are inside hi")
hi()
Upvotes: 0
Reputation: 13085
You need a loop for this. Try this instead
for _ in range(4):
print("we are inside hi")
Upvotes: 0