Python到目前为止一直都是自学,用到什么学什么。但是最近发现自己相关的知识掌握并不全面,同时又想深入学习爬虫和表格处理,故进行补充和梳理,方便复习,参考视频资料:
1.用Python玩转数据 南京大学 张丽
2.Python网络爬虫与信息提取 北京理工大学 嵩天
>>> dir(__builtins__) # 查看异常名、属性名、内建函数名
>>>help(zip) # 查看帮助
语法:
def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
实例:
>>> def printme( str ):
... "打印传入的字符串到标准显示设备上"
... print(str)
... return
...
>>> printme("!@@")
!@@
>>> print(printme.__doc__)
打印传入的字符串到标准显示设备上
>>> def f(x,y = True):
... if y:
... print(x,'and y both correct')
... print(x,'is OK')
...
>>> f(68)
68 and y both correct
68 is OK
>>> f(68,False)
68 is OK
>>> f(y = False, x = 68)
68 is OK
函数可以像参数一样传递给另外一个函数。
>>> def addMe(x):
... return x+x
...
>>> def self(f,y):
... print(f(y))
...
>>> self(addMe,2.2)
4.4
>>> r = lambda x:x+x
>>> r(5)
10
>>> x = range(3)
>>> x
range(0, 3)
# 生成器 lazy list
>>> for i in x:
... print(i)
...
0
1
2
# 左闭右开,默认步长为1,默认起始值为0
>>> list(x)
[0, 1, 2]
如果循环代码从break处终止,跳出循环;正常结束循环,则执行else中代码。
>>> for i in range(1, 10, 2):
... if i % 5 == 0:
... print("Bingo!")
... break
... else:
... print(i)
...
Bingo!
>>> a = 3
>>> def f():
... a = 5
... print(a ** 2)
...
>>> f()
25
>>> a
3
>>> def f(x):
... print(m)
... m = 5
... print(m + x)
...
>>> m = 3
>>> f(8)
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in f
UnboundLocalError: local variable 'm' referenced before assignment
>>> def f(x):
... global m
... print(m)
... m = 5
... print(m + x)
...
>>> m = 3
>>> f(8)
3
13
>>> print(m)
5
Python中每个异常都是类的实例,用异常对象表示异常情况。