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

How to use the for statement in Python

編輯:Python

Python Medium for Statement to traverse a sequence (sequence) All elements in , The sequence here can be a list (list) Or string (string).Python For the use of lists and strings in, please refer to 《Python in List How to use 2-1》、《Python in List How to use 2-2》、《Python How to use strings in 2-1》 and 《Python How to use strings in 2-2》.

1 Basic grammar

for The basic syntax of a sentence is :

for Variable in Sequence :
    sentence 1

among ,“ Sequence ” That is, the list or string to be traversed ;“ Variable ” Is the element in the sequence . Every time you get one “ Sequence ” The elements in , Just do it once “ sentence 1”, Until traversal “ Sequence ” All elements in .

2 Usage method

Use for Code to traverse elements in a sequence , Pictured 1 Shown .

chart 1 Go through the elements in the list

among ,squares Is a list of , adopt for Statement traversal squares All elements in . Every time squares An element in , Save the value of this element to a variable i in , And print out i The value of , Until traversal squares All elements in .

chart 2 The code shown in goes through all the characters in the string .

chart 2 Traversing characters in a string


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