程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[python] use while and for to loop through the list

編輯:Python

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 .

One 、while Loop traversal

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 :

Two 、for Loop traversal

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved