Python path-basics-8 cycles, python path basics-8
There are two types of loops in python: for Loop and while loop. The loop can iterate the data in the sequence:
For Loop
The for loop iterates each element in the list, tuple, or string sequentially. for example:
Names = ["zhangcong", "lisanjiang", "pangzhiguo"] for name in names: print name # execution result zhangconglisanjiangpangzhiguo
So for x in... Loop is to assign each element to variable x and then execute the indent statement.
For example, 1-10 must be calculated.
Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum = 0for I in numbers: sum + = I # sum + = I = sum + I here is just short for print sum # execution result 55
Here, the list can also be replaced by range. The range () function can generate an integer sequence. For example, the sequence generated by range (5) is an integer smaller than 5 from 0 ::
Sum = 0for I in range (1, 11): sum + = iprint sum # execution result 55 officially explains the range (...) range (stop)-> list of integers range (start, stop [, step])-> list of integers Return a list containing an arithmetic progression of integers. # Return an integer list containing an arithmetic difference series. Range (I, j) returns [I, I + 1, I + 2,..., J-1]; start (!) Ults to 0. when step is given, it specifies the increment (or decrement ). for example, range (4) returns [0, 1, 2, 3]. the end point is omitted! These are exactly the valid indices for a list of 4 elements.
While Loop
While loop: as long as the condition is met, it will be used in an endless loop. For example, to calculate the sum of all odd numbers within 100, you can use the while loop:
# The Variable n in the loop is continuously reduced until it is changed to-1, and the while condition is no longer met. The loop exits sum = 0n = 99 while n> 0: sum = sum + n = n-2 print sum
Break
Break: jumps out of the current loop and the loop ends.
For example, print 1-100 and exit the loop when I> 50.
I = 1 while True: if I> 50: break print I + = 1 Output: 12345678 ...... 474849
Continue
Continue: jump out of this loop and perform the next loop
For example, print 1-10, but do not contain 5
For I in range (11): if I = 5: continue print I # execution result 1234678910