Similar to the Python judgment statement, Python also has
Looping StatementsLike what
for,
whileWait, in
Looping Statements, if the condition set is not so accurate, it will enter the infinite loop, then the page will give the system error, or the computer will directly
crashes。
So what is a loop?
For example, to calculate 1+2+3, we can write an expression directly:
>>> 1 + 2 + 36
To calculate 1+2+3+...+10, you can barely write it.
However, to calculate 1+2+3+...+10000, it is impossible to write the expression directly.
In order for the computer to calculate thousands of repetitions , we need to loop the statements .
There are two types of Python loops, one is the for...in Loop, and each of the elements in the list or tuple is iterated in turn to see an example:
names = [' Michael ', ' Bob ', ' Tracy ']for name in Names: print (name)
Executing this code, each element of the names is printed sequentially:
Michaelbobtracy
So for the x in ... A loop is a statement that puts each element into the variable xand then executes the indented block.
For example, if we want to calculate the sum of 1-10 integers, we can use a sum variable to do the summation:
sum = 0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]: sum = sum + xprint (sum)
If you want to calculate the sum of 1-100 integers, writing from 1 to 100 is a bit difficult, but fortunately Python provides a range () function that generates an integer sequence that can be converted to a list by using the list () function. For example, the series generated by range (5) is an integer starting from 0 that is less than 5:
>>> List (range (5)) [0, 1, 2, 3, 4]
The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting the loop when the condition is not satisfied. For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:
sum = 0n = 99while n > 0: sum = sum + N n = n-2print (sum)
The loop internal variable n is continuously self-reducing until it becomes 1, and the while condition is no longer satisfied, and the loop exits.