1

i wrote this python code in python3.

def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
         return
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

in the above code if i replace the return with the "break" statement, then it still work fine.

I am looking for more clarification on the usage of "Return" vs "Break" from this particular code perspective.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 1
    Answered here: [what is the difference between return and break in python?](https://stackoverflow.com/questions/28854988/what-is-the-difference-between-return-and-break-in-python) – 0xedb Feb 03 '20 at 03:06
  • what is your question? – eyllanesc Feb 03 '20 at 03:09
  • 1
    If you `break` out of the `while` loop, the function runs to the end and returns. Either way, you return. – Mark Feb 03 '20 at 03:09
  • 2
    In your particular case there is no difference since after the loop nothing is executed. – eyllanesc Feb 03 '20 at 03:10
  • You use `return` to completely end a function, and go out one layer of scope. If you have a function, with a nested one beneath it, and write `return` in the second function, as soon as it runs that `return`, it will go back out to the first function. If the first function returns, it goes out to global scope. `break` breaks away from a loop, such as a `for` or `while` loop. That causes the loop to end at that point, and not run any other code in the loop. Hope that helps. – OakenDuck Feb 03 '20 at 03:16

0 Answers0