Ask your own question, for FREE!
Computer Science 16 Online
OpenStudy (anonymous):

Could some please explain me how for loops and while loops work with lots of detail and even with some examples (I am familiar with python language that is what we are using in class) and if you know how to convert for loops into while loops pleasee

OpenStudy (anonymous):

In Python, you can use a for loop to go through each element in a list. For example: a = [1,2,3,4,5,6,7,8,9,10] for e in a: print e will go through all elements in a and print them. (for most other languages, for loops will work a bit differently) A while loop is a loop where you do something as long as a certain condition is met. For example, you could print all numbers smaller than 6 with the following code: a = [1,2,3,4,5,6,7,8,9,10] i = 0 while( a[i] < 6 ): print a[i] i += 1 As long as the condition (a[i] < 6) is met, the loop will print a[i] and then increment i (so you can inspect the next element of a). To convert a for loop into a while loop, you can use the example from the while loop and adjust the condition. E.g. it could check whether i is still within the range of the array.

OpenStudy (anonymous):

wow you guys are truly amazing thanks a lot guys really appreciate it

OpenStudy (anonymous):

Two additions: 1. A for loop (in Python) basically IS a while loop, but with two simplifications. The condition is always "keep going until you reach the end of the list" and the iterative step is always "move on to the next element of the list." 2. A for loop in Python is not really quite the same thing as a for loop in most other languages. For example, in C++, a for loop has three parts: an initialization of an iterative variable, a condition, and an iterative step. So, in C++ you might see something like: for (n=1;n<=10;n++) { cout << n; } which would just print out the numbers 1 through 10.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!