Python 学习笔记之语法(一)
2015-07-21 10:15
681 查看
1、书写规范
Python对语法格式要求很严格,因此,在编写时一定要注意这些问题,比如下面就是这样的问题:Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\anzhuang\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile execfile(filename, namespace) File "D:\anzhuang\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Users/wt/.spyder2/template.py", line 12 print isinstance(a, int) ^ IndentationError: unexpected indent
IndentationError: unexpected indent, 通过这错误提示,就可以明白在编写代码时,存在不严格的书写规范,而产生这样的错误。
原因是:可能tab和空格没有对齐,需要检查下tab和空格
2、可变和不可变对象
大部分Python对象是可变的,比如列表、字典、数组以及大部分用户定义的类型,而其他的如字符串和元组则是不可变的3、异常处理
print float((1, 2)),会先如下错误Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\anzhuang\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile execfile(filename, namespace) File "D:\anzhuang\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Users/wt/.spyder2/template.py", line 7, in <module> print float((1, 2)) TypeError: float() argument must be a string or a number
可能需要处理ValueError,因为TypeError可能意味着你的程序中存在合法性bug。要达到这个目的,在except后面加上异常类型即可
def attempt_float(x): try: return float(x) except (TypeError, ValueError): return x print attempt_float((1, 2))
只需编写一个异常处理的元组即可捕获异常
如果不想处理异常,而只希望有一段代码不管try块代码成功与否都能被执行。但最后finaly即可达到目的
4、def 用法
def 是定义函数的,如下:菲波那切数列函数>>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while a < n: ... print(a, end=' ') ... a, b = b, a+b ... print() ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
5、元组
元组(tuple)是一种一维的、定长的、不可变的Python对象序列,最简单的创建方式是一组以逗号隔开的值。5.1 例子
5.1.1
tuple = 4, 5, 6 print tuple
输出结果:(4, 5, 6)
5.1.2
tup = tuple('sjkfhvhv') print tup
输出结果:(’s’, ‘j’, ‘k’, ‘f’, ‘h’, ‘v’, ‘h’, ‘v’)
但在第一次测试时,出现了如下错误
python TypeError: 'str' object is not callable
不知是什么原因,在网上找了很多,网上说的有,变量名有Python api有重名的,但都不能解决。后来,重启下就好了,很无语。
5.2 元组方法
由于元组的大小和内存是不可修改的,其使用方法很少,用的最多是count方法,用于计算其指定值出现的次数a = (1, 2 ,2, 3, 5, 6, 2, 2) print a.count(2)
输出结果是:4
6 列表
跟元组相比,列表是可变长的,而且其内容是可以修改的,通过方括号或list函数来定义:6.1 例子
6.1.1
tup = ('foo', 'bar', 'baz') b_list = list(tup) b_list[1] = 'jldaj;l' print b_list
6.1.2
tup = ('foo', 'bar', 'baz') b_list = list(tup) b_list[1] = 'jldaj;l' b_list.append('khalkhlk') b_list.insert(1, 'hlakhl') b_list.remove('foo') print b_list
7 切片
通过切片标记法,你可以选取序列的类型(数组,元组,NumPy数组等)的子集,其基本形式由索引运算符以及传入其中的start:stop构成。start或stop都是可以省略的,此时分别默认序列的起始和结尾处。
seq = [1, 2, 2, 3, 4, 6] print seq[:5]
负数索引从索引的末尾开始切片:
seq = [1, 2, 2, 3, 4, 6] print seq[-4:]
运行结果:[2, 3, 4, 6]
多个冒号的情况
seq = [1, 2, 2, 3, 4, 6] print seq[::2]
第二冒号后面是步长。
Zip
将多个序列(列表)中的元素配对,从而产生一个新的元素列表seq = [1, 2, 2] seq2 = ['one', 'two', 'there'] print zip(seq,seq2)
运行结果:[(1, ‘one’), (2, ‘two’), (2, ‘there’)]
zip可以接受任意数量的序列,最总得到的元组数量由最短的序列决定。
seq = [1, 2, 2, 3] seq2 = ['one', 'two', 'there'] print zip(seq,seq2)
运行结果:[(1, ‘one’), (2, ‘two’), (2, ‘there’)]
相关文章推荐
- 一个简单的python闭包例子
- Python 线程和定时器
- Google's Python Class(五)——Python 字典和文件
- Python 中"元类"
- Python中修饰器
- Python中的设计模式
- Python高级特性之:List Comprehensions、Generator、Dictionary and set comprehensions
- Python 符号计算的瑞士军刀——SymPy
- 详解Python的Django框架中inclusion_tag的使用
- Python:列表生成式
- python 列表生成式
- Python多线程学习
- 如何像Python高手(Pythonista)一样编程
- python反转字符串(简单方法)及简单的文件操作示例
- python Tips系列:判断list是否为空
- PYTHON单元测试
- Python_12-线程编程
- 【python learing】玩玩pythonanywhere
- Python文件操作
- Python的高级特性7:闭包和装饰器