Python学习笔记_01

1.当遇到IndentationError:unexpected indent错误时,说明代码的缩进量不一致,使用Notepad打开Python源文件,然后选择显示所有隐藏的字符即可看到代码中的缩进量,可以看到有的地方是用空格缩进的,有的地方是用Tab键缩进的,这在Python中是不允许的,会报IndentationError:unexpected indent错误

2.在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。
举例如下:
#程序源代码
count = 0
while count < 5:
    print count,'is less than 5'
    count += 1
else:
    print count,'is not less than 5'
#程序执行结果
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
#程序源代码
count = 0
while count < 5:
    print count,'is less than 5'
    count += 1
    if count == 5:
        break
else:
    print count,'is not less than 5'
#程序执行结果
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5

 3.Sequence序列(原文详见http://www.cnblogs.com/vamei/archive/2012/05/28/2522677.html)

Sequence序列有两种,tuple和list。tuple和list的主要区别在于,一旦建立,tuple的各个元素不可再变更,而list的各个元素可以再变更。

一个序列可以作为另外一个序列的元素,如:s = [1,[3,4,5]],这里有一个注意点,引用s中的1的方式是s[0];同理,当s  = [[1,2],3],引用s中的3的方式是s[1]

其他的引用方式:

范围引用: 基本样式[下限:上限:步长]

>>>print(s1[:5])             # 输出s1中下标0到4的元素

>>>print(s1[2:])             # 输出s1中下标从2到最后的元素

>>>print(s1[0:5:2])        # 从下标0到下标4 (下标5不包括在内),每隔两个取一个元素 (即取下标为0,2,4的元素)

>>>print(s1[2:0:-1])       # 从下标2到下标1

从上面可以看到,在范围引用的时候,如果写明上限,那么这个上限本身不包括在内。

尾部元素引用

>>>print(s1[-1])             # 序列最后一个元素

>>>print(s1[-3])             # 序列倒数第三个元素

同样,如果s1[0:-1], 那么最后一个元素不会被引用 (再一次,不包括上限元素本身)

 

 



 

posted @ 2017-03-09 15:51  swsut_wjy  阅读(246)  评论(0编辑  收藏  举报