Aug-23-2018, 06:26 PM
(Aug-23-2018, 05:43 PM)6pathsMadara Wrote: Below is the code I have done following a tutorial, it involves creating a generator that makes the Fibonacci sequence, and then prints it out for values under 100. My problem that I have is I don't understand why I am using 'yield a' and what this does. Code is below:def fib(): a = 0 b = 1 while True: yield a a = b b = a + b for f in fib(): if f > 100: break print(f)
(Aug-23-2018, 05:59 PM)Larz60+ Wrote: You capture the value (a from fib in your loop) returned by fib, but don't do anything with it except for the last iteration. you should save it to a list, or print out results immediately: to list:But I still don't understand what yield does, when i remove it, the code doesn't do anything, there's no errors but it doesn't do anything, but I still don't understand it's functionality.def fib(): a = 0 b = 1 while True: yield a a = b b = a + b fibs = [] for f in fib(): fibs.append(f) if f > 100: break print(fibs)immediate:def fib(): a = 0 b = 1 while True: yield a a = b b = a + b for f in fib(): print('{}, '.format(f), end = '') if f > 100: break print()