Can anybody tell me what is the difference between while loop and yield in detail with suitable example ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Can anybody tell me what is the difference between while loop and yield in detail with suitable example ?

30th Oct 2018, 9:17 AM
Divyanshu Singh
Divyanshu Singh - avatar
2 Answers
+ 3
While and yield are quite different actually. While is a loop executing a block of code until the condition is false. Yield is used in generators, which are quite similar to functions. A while loop can be used like this: x = 1 while x < 5: print("in a loop") # prints 4 times x += 1 A generator(yield) can be used like this: def generator(): # a generator is a function that has the keyword yield in it x = 1 while x < 5: yield x x += 1 my_gen = generator() print(my_gen) # prints out generator object at a certain location # a generator is also an iterator for i in my_gen: print(i) # output: 1234 The yield keyword is similar to the return keyword but it does not end the function but pauses only to resume when it's __next__ method is called There are a whole lot more you can do with while and yield which I did not explain
30th Oct 2018, 9:50 AM
jtrh
jtrh - avatar
+ 3
Those are two totally different things. A while loop just executes as long as certain condition is met. e.g. i = 1; while(i<4): print(i) i += 1 prints 1 2 3 yield is quite similar to a return statement, but used in generators. For example you can use a function like def simplegen(): yield 6 yield 3 and call it via for i in simplegen(): print(i) will output 6 3 You can also combine while and yield def advancedgen(end): i = 0 while(i<end) yield i i += 2 for i in advancedgen(10) print(i) will output 0 2 4 6 8
30th Oct 2018, 10:01 AM
Matthias
Matthias - avatar