Question:
Please explain the differences between for
and while
loops.
If possible in simple language. Thank you.
Answer:
Using the range(n)
function as an example:
In the loop for i in range(n)
each value from the range range(n)
will be written to the variable i
in turn, for example:
In [1]: for i in range(3):
...: print(i)
...:
0
1
2
First i
takes the value 0
, then 1
, and so on until we get to n
.
Also cycle for
possible to walk on any iterability object, for example:
In [4]: array = [1, 2, 3]
In [5]: for i in array:
...: print(i)
The variable i
will one by one be written the values from the list array
.
The while
works a little differently, it checks the condition for truth, while x < 10
– at each iteration of the loop, it will check x < 10
, if so, the loop will go further, using the example of the same range(n)
:
In [2]: i = 0
In [3]: while i < 3:
...: print(i)
...: i += 1
...:
0
1
2
At each iteration, we check whether the variable i
is less than 3
, if so, then we output the value of the variable i
and add one to it, we repeat this until the check for i < 3
returns False
. We are essentially saying, as long as something is true, then take some action.
Remember the for
loop example when we were looping through the list? With while
the situation is different, we need to pull elements from the list by their indices, that is, the condition will look like this: while i < len(array)
, the len(iterable)
function will return us the number of elements in the list, for example same array
:
In [6]: i = 0
In [7]: while i < len(array):
...: print(array[i])
...: i += 1
To define an infinite while
, you must specify a condition that is always true, such as while True
.
With the cycle for
more complex, infinite loop explicitly is impossible, as the cycle for
finishes its work when the pass through all elements of the object, therefore it is necessary to pass on such an object, which is infinite elements, then we can help generators , to talk about them in detail I I will not, since the topic is quite extensive, I will only show a small example with the itertools
module:
In [11]: from itertools import count
In [12]: for i in count():
...: print(i) # 1, 2, 3, 4 ...
Thus, we have defined an infinite for
loop, count
also takes 2 optional arguments, start
number from which we will start the iteration, and step
the step itself.
Here you can find some cycle problems for practice.