函数
- 语法
def <function> (<formal parameters>):
<function body>
def max(x,y):
if x>y:
return x
else:
return y
x = float(raw_input('Enter a number:'))
p = int(raw_input('Enter an integer power:'))
result = 1
for turn in range(p):
print('iteration: '+str(turn)+
'current result: '+str(result))
result = result*x
def iterationPower(x,p):
result = 1
for turn in range(p):
print('iteration: '+str(turn)+
'current result: '+str(result))
result = result*x
return result
变量绑定
- 每一个函数调用都会创建一个新环境,新作用域,形式参数与输入数值在这里绑定,而我们看见的局部变量,只在函数内部有效。
- 这种辖域通常被称为静态(static)辖域或者语汇(lexical)辖域,因为在此辖域内,变量的数值有代码界限定义。
另一个例子
def square(x):
return x*x
def twoPower(x,n):
while n>1:
x = square(x)
n = n/2
return x
x = 5
n = 1
print(twoPower(2,8))
#输出为256
- 更有趣的一个例子,找到根
#对于负数来说逻辑不成立
def findRoot1(x,power,epsilon):
low = 0
high = x
ans = (high+low)/2.0
while abs(ans**power-x)>epsilon:
if ans**power < x:
low = ans
else
high = ans
ans = (low+high)/2.0
return ans
#对负数求根做出改进
def findRoot2(x,power,epsilon):
if x<0 and power%2==0
return none
#如果是负数,则最小值改为x
#如果是正数,则最大值改为x
low = min(0,x)
high = max(0,x)
ans = (high+low)/2.0
while abs(ans**power-x)>epsilon:
if ans**power < x:
low = ans
else
high = ans
ans = (low+high)/2.0
return ans
#再对小数求根做出改进
def findRoot3(x,power,epsilon):
if x<0 and power%2==0
return none
#如果是小数,则搜索范围变成了(-1,1)
low = min(-1,x)
high = max(1,x)
ans = (high+low)/2.0
while abs(ans**power-x)>epsilon:
if ans**power < x:
low = ans
else
high = ans
ans = (low+high)/2.0
return ans
- 一名优秀的程序员必备:添加规范
def findRoot3(x,power,epsilon):
"""
x and epsilon int or float, power an int
epsilon >0 & power >=1
returns a float y
y**power is within eplison of x
If such a float does not exist, it returns None
"""
函数包
- 把函数保存成一个.py文件,如:circle.py
- 导入方法很简单,如:import circle,即可。
- 调用方法也很简单,如:#得到circle文件中pi变量的值 circle pi #调用了circle文件中的area函数 circle.area(3)
- 修改函数包,覆盖原来内容
from circle import * #修改了pi的值 pi = 0.0
附:Python 字符串函数的方法
http://blog.youkuaiyun.com/zhangj1012003_2007/article/details/5559182string.find()与string.index():
S.find(substr, [start, [end]]) #返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索
S.index(substr, [start, [end]]) #与find()相同,只是在S中没有substr时,会返回一个运行时错误