函数
语法:
返回none 或者指定值
函数内部为一个黑盒
封装(encapsulating)一个环境局部,不影响全局环境,便于调试
全局变量和局部变量
例:幂函数
def iterativePower(x,p):
result=1
for turn in range(p):
print('iteration: '+str(turn)+' current result: '+str(result))
result*=x
return result
例:求根1(只能求正的、大于一的)
def findRoot1(x,power,epsilon):
low=0
high=x
ans=(low+high)/2
while abs(ans**power-x)>epsilon:
if ans**power<x:
low=ans
else:
high=ans
ans=(low+high)/2
return ans
例:求根2(只能求绝对值大于1的)
def findRoot2(x,power,epsilon):
low=min(0,x)
high=max(0,x)
ans=(low+high)/2
while abs(ans**power-x)>epsilon:
if ans**power<x:
low=ans
else:
high=ans
ans=(low+high)/2
print(ans)
return ans
例:求根3(针对所有实数)
"""x and epsilon int or float,power an int
epsilon>0 & power>=1
return a float y s.t. y^power is within epsilon of x.
If such a float does not exist, it returns None
"""
def findRoot3(x,power,epsilon):
if x<0 and power%2==0:
return None
#can't find even powered root of negative number
else:
low=min(-1,x)
high=max(1,x)
ans=(low+high)/2
while abs(ans**power-x)>epsilon:
if ans**power<x:
low=ans
else:
high=ans
ans=(low+high)/2
return ans
好的代码应该有对于输入的假设和输出的描述,以及不同输入下的报错说明。
上面三个例子说明,封装函数便于更改算法实施。
函数可以由使用者重新创造并作为原语使用
函数可以将问题分解成小的模块,分别解决问题的一部分或者一个步骤
函数可以隐藏细节,让用户直接调用于解决其他的问题
引入py文件
可以用py文件装载具有某种共性的一系列函数
1 import X
在使用X.py中的函数x(y)时,要写:
X.x(y)
2 form X import *
在使用X.py中的函数x(y)时,要写:
x(y)
针对字符型的一些函数
.capitalize()
Return a copy of the string with its first character capitalized and the rest lowercased.
>>> str3='aBBN'
>>> str3.capitalize()
'Abbn'
.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
>>> str2 = 'number one - the larch'
>>> str2.find('e',5,)
9
.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.