您的位置:首页 > 编程语言 > Python开发

Python入门教程-13 for-in

2015-07-22 20:25 615 查看

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
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: