本文主要是介绍Python入门教程-13 for-in,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 循环
for-in是Python中表示循环的其中一种方法。
2. 基本语法
示例:
>>> values = ['first', 'second', 'third']
>>> for value in values:
... print value
...
first
second
third
>>>
for循环对于列表中的数据类型是不关注的,比如list存放的是tuple这种类型:
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> values = [('Tom', 23), ('John', 18), ('Ann', 20)]
>>> for value in values:
... name, age = value
... info = "name=%s, age=%d" % (name, age)
... print(info) # in Python 3.4
...
name=Tom, age=23
name=John, age=18
name=Ann, age=20
>>>
3. break和continue
python的循环体中也可以使用break和continue语句,功能和语法和C/C++一样。
>>> items = range(1, 20, 2)
>>> items
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> for item in items:
... if item % 3 == 0: pass
... print item
... if item >= 17: break
...
1
3
5
7
9
11
13
15
17
>>>
这篇关于Python入门教程-13 for-in的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!