Traversal is to access each data in sequence , This operation is called traversal . For example, there is a demand , The requirement content is : Print each data in the list in turn . This traversal program uses while Loop or for The cycle can be completed .
demand : Print each data in the list in turn .
Code experience :
"""
1. Prepare data representing subscripts
2. loop while
Conditions : i<3 --- Conditions cannot be written dead , Last use len() Instead of
Traverse : Access each data of the sequence in sequence
i += 1
"""
list1 = ['python', 'java', 'php']
i = 0 # Because the list subscript is from 0 Start
while i < len(list1): # len() List length
# The list subscript cannot be fixed, or the same data will be output all the time , and i Related , With i To output the list data in turn
print(list1[i])
i += 1
Execution results :
demand : Print each data in the list in turn .
Code experience :
list1 = ['python', 'java', 'php']
for i in list1:
# Traverse the data in the data
print(i)
Execution results :
summary : Through the above two loop traversal codes, it is obvious that for The code of loop traversal is better than while A lot less , Generally, if the work involves traversing the data in the sequence, it is generally preferred to for loop , Because the syntax is simpler and the amount of code is less . So is the above python Introductory tutorial It belongs to the elementary knowledge point , Suitable for Xiaobai to learn .