1: First
2: Knowledge Summary
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 will print names
each element in turn:
michaelbobtracy
so for x in ...
The loop is to put each element into a variable x
, and then executes the indented block of the statement.
For example, if we want to calculate the sum of 1-10 integers, we can use a sum
variable to accumulate:
sum = 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, such as range (5), which generates a sequence that is less than 0, starting from 5:
>>> range(5)[0, 1, 2, 3, 4]
Range (101) can generate a sequence of 0-100 integers, calculated as follows:
sum = 0for x in range(101): sum = sum + xprint sum
Please run the above code on your own, to see if the result is 5050 of the students ' mental arithmetic.
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
Try
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 Learning: Two loop statements for and while