Quantcast
Channel: LinE's Blog
Viewing all articles
Browse latest Browse all 25

Python第八课:流程控制_for-in – 笔记

$
0
0

视频打包下载

下载地址:http://pan.baidu.com/s/1c02HoZm 密码: 03va

我自己做的笔记

https://onedrive.live.com/view.aspx?resid=27079372A35C6C12!350&app=OneNote&authkey=!AK-RNvDHBnuJHXM

主要知识点

for在python是循环的一种方式,目的是为了让一段代码反复的执行,直到序列迭代(依次读取并赋值)完成
被迭代变量有多少个元素,for循环就执行多少次
for格式遵循代码缩进原则

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = "abcd"  # 定义一个字符串序列
for x in a:  # 从a中依次读取每一个元素并赋值给x
    print "x = " + x
b = ('213', '123', 'asd', 'zxc')  # 定义一个元组序列
for y in b:  # 从b中依次读取每一个元素并赋值给y
    print "y = " + y

• for循环也可以使用else语句,即for-in-else

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
str1 = "abcdefg"
for x in str1:  # 依次取str1的元素并赋值给x
    print x  # 打印出x
else:  # for循环完成以后
    print "Finish"  # 打印出Finist

range函数
range(i, j, [step])
1. 如果创建的对象为有序数列,可以使用range()函数
2. i 为初始值,可以省略,省略后表示从0开始
3. j 为终止值,但不包括j本身,即循环j-1次
4. step为步进值,表示每过几个数输出一次
例子

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print range(0, 11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print range(0, 11, 2)
[0, 2, 4, 6, 8, 10]
print range(0, 11, 3)
[0, 3, 6, 9]

○ 遍历字符串

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = "abcdefghijklmn"
for x in a:
    print x

○ 遍历元组

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = ("ab",'cd','ef','gh','ij','kl','mn')
for x in a:
    print x

○ 遍历列表

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = ['qw','er','ty','as','df','gh']
for x in a:
    print x

○ 遍历字典

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = {
    'a': 'qwe',
    'b': 1,
    'c': 234,
}
for x in a:
    print x

用items()方法遍历整个字典,返回的值为元组,迭代赋值给x,y

###############__Code__###############
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = {
    'a': 'qwe',
    'b': 1,
    'c': 234,
}
for x, y in a.items():
    print x
            print y


Viewing all articles
Browse latest Browse all 25

Trending Articles