1. for x in ...
a loop is a statement that puts each element into a variable and x
then executes the indented block. iterate through each element of the list or tuple in turn.
For example, if we want to calculate the sum of 1-10 integers, we can use a sum
variable to accumulate:
0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: 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 a sequence of integers that list()
can then be converted to a list by a function. For example, range(5)
the generated sequence is an integer starting from 0 and less than 5:
list(range(5))[0, 1, 2, 3, 4]
range(101)
You can generate an integer sequence of 0-100, which is calculated as follows:
0for x in range(101): sum = sum + xprint(sum)
Practice:
The purpose of this exercise is not to understand the role of X ... After I wrote it, I felt more deeply.
2. While loop, as long as the condition is satisfied, it loops continuously and exits 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:
0n = 99while n > 0: sum = sum + n n = n - 2print(sum)
The loop internal variable is n
continuously self-reducing until -1
it becomes, and the while condition is no longer satisfied, and the loop exits.
python--review two kinds of circulation