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》.
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 .
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