+ 3

[DUPLICATE] Use of while vs. for loops

Can someone give a few basic examples of when to use while or for loops? Thanks!

19th Feb 2018, 9:18 PM
Maddie
Maddie  - avatar
6 Answers
+ 30
when u want to execute coditions a known number of time , then its always better to use a for loop & when u want e execute statements till condition is true , then its better to use while loop its not some rule , depends on your wish ... U can use while loop also in place for loop .
20th Feb 2018, 2:40 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 7
for loop: iterating through items in a list/string or iterating through indexes to get items in a string/list while loop: (dont really use it that often but if i do its because i want a specific input from the user so until that criteria is met it wont allow them to continue)
19th Feb 2018, 9:28 PM
Obbu
Obbu - avatar
20th Feb 2018, 2:45 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
playGame = True while playGame == True do this if this playGame == False while evaluates a bool so the loop will not end until the value is false or true depending on your setup. So if you don't know how many times you will need to run choose a while loop. if you need a known number or an irritable loop go with for. steps = 5 for row in range(steps) for col in range(row) print(" ",end = "") print('#') this only needs to run steps times. so first in runs the outer loop and prints # then the inner and prints a space and then # and so on until my 5 steps are met. Not real code for the most part but what is real is based on python. Idea is the same though.
19th Feb 2018, 9:39 PM
emmey
emmey - avatar
+ 4
For loops are used to iterate through items. For example, if you wanted to go through a list and see if any of the items in the list equal a certain value, then you’d use a for loop. While loops are used when you don’t know how long the loop is specifically going to cycle through the code. For example you may make a game where you want the player to be able to move while the game is running so you’d put that in a while loop. I hope this helps, and happy coding!
19th Feb 2018, 10:59 PM
Bridgetn58
Bridgetn58 - avatar
+ 3
in a very simple manner: use while when u dont know how many times you want to repeat your code use for when u do know
19th Feb 2018, 10:19 PM
Dominique Abou Samah
Dominique Abou Samah - avatar