could someone please give me examples in how to turn a for loop into a while loop with as much as details as possible please (in python language)
It's one of those things that depends on the situation, but I'll give you an example. Let's say I have the following code: for x in range(10): print x This code is about as simple as you can get. It takes a list from 0 to 9, and walks through the list. For each new element in the list, it prints that element. Once it gets to the end of the list, it's done. Now, while loops are missing two things that are automatic in a for loop: they don't know how to automatically change the iterator (in the for loop, x automatically goes to the next element, then the next, then the next, etc), and they don't know when they're done (a for loop is automatically done when x gets to the end of the list). So you need to declare a variable that will change until it gets to a certain ending point. You need to tell the while loop when to break out, and in the while loop, you need to either change the variable somehow so that you'll break out of the loop, or you need to break manually using "break". Here's the same code using a while loop: x = 0 while x < 10: print x x += 1 Notice that I told the loop where to start instead of just assuming it's starting at the beginning of a list. I then told the loop to keep going until x is not less than 10 anymore, and every time I go through the loop, I add 1 to the variable, changing its state.
Join our real-time social learning platform and learn together with your friends!