通过for ... in ...:的语法结构,我们可以遍历字符串、列表、元组、字典等数据结构。
注意python语法的缩进
字符串遍历
>>> a_str = "hello itcast" >>> for char in a_str: ... print(char,end=' ') ... h e l l o i t c a s t
列表遍历
>>> a_list = [1, 2, 3, 4, 5] >>> for num in a_list: ... print(num,end=' ') ... 1 2 3 4 5
元组遍历
>>> a_turple = (1, 2, 3, 4, 5) >>> for num in a_turple: ... print(num,end=" ") 1 2 3 4 5