While working with return statement print statement will not work?

def f(n):
for i in range(1,n):
return i
print(“ok”)

print(f(9))

it returns only i value but doesnot print anything could any one clarify please i am confussing

The moment you return something, the function is terminated. So anything after the return statement does not get executed.

And please format your code.

2 Likes

Because function ends with return statement.Once you return its over.So it doesn’t print ok beacuse function finish as soon as returns countered

You include the print ok statement inside the return …it will print…because you put the statement outside the loop

it will work if you use print statement before return
“return” statement for functions is like break statement for loops. The function will get terminated and any lines of code after that inside the function will be neglected

def f(n):
   for i in range(1,n):
       return i
   print(“ok”)

print(f(9))

format your code using (```) at the beginning and end of the code

The formatted version you’ve posted is still broken, though.

This is better:

def f(n):
    for i in range(1,n):
        return i
    print("ok")

print(f(9))

Although it could equally well be:

def f(n):
    for i in range(1,n):
        return i
        print("ok")

print(f(9))

which is why it’s so important for the original poster to format their code in the first place :man_shrugging:

1 Like

yeah sorry. I did use tab, didn’t notice that it didn’t work :flushed: :dizzy_face:

1 Like

hello sir,thank you for your explanation . I would like to ask one question regarding to time complexity .As time complexity is needed for any program.So how can time complexity be learned .Can you suggest some best sites . could you please say it sir???

This playlist is good. It will teach you the basics.

1 Like