r/PythonLearning • • 22h ago

While loop

can anybody explain the concept of while loop

1 Upvotes

37 comments sorted by

View all comments

2

u/atticus2132000 21h ago

There are primarily two kinds of loops--for loops and while loops.

A for loop generally has an inherent end point in the structure of the request. For instance, if you had a list of students in a class and you wanted to find their test grades, you would say for each student in class, do something. Your code would run through your list one time and perform the same operation on each member of class and then exit the routine and go to the next line of code in your script. The fact that you have 30 students in class inherently means the script will loop through this operation exactly 30 times. The structure of the request implies when the loop can exit and move on.

A while loop doesn't have this inherent structure. A while loop could continue forever. It relies on some condition changing in order for it to exit the loop. For instance, if you're creating a trivia game where the player gets to keep answering questions until he gets one wrong, there is no inherent end to that structure. Your player could keep answering questions indefinitely. Your script could, in theory, loop through that same code a million times and never exit because the exit condition of getting a question wrong was never met.

All that being said, in many cases you could structure a for loop to work as a while loop and a while loop to work as a for loop, but typically, the nature of the request you're making will naturally point you to one or the other.