函数定义:
def 函数名(参数):
执行语句
函数调用的一般格式:函数名(参数)
def happy():
print("Happy birthday to you!")
def sing(person):
happy()
happy()
print("Happy birthday,dear",person+"!")
happy()
def main():
sing(""Mike)
print()
sing("Lily")
print()
sing("Elmer")
main()
return语句返回值传递给调用程序,返回值可以是一个变量也可以是一个表达式。
计算三角形周长:
import math
def square(x):
return x*x
def distance(x1,y1,x2,y2):
dist=math.sqrt(square(x1-x2)+square(y1-y2))
return dist
def isTriangle(x1,y1,x2,y2,x3,y3):
flag=((x1-x2)*(y3-y2)-(x3-x2)*(y1-y2))!=0
return flag
def main():
print("Please enter (x,y) of three points")
x1,y1=eval(input("Point:(x,y)="))
x2,y2=eval(input("Point:(x,y)="))
x3,y3=eval(input("Point:(x,y)="))
#判断三个点是否构成三角形
if(isTriangle(x1,y1,x2,y2,x3,y3)):
#计算周长
perim=distance(x1,y1,x2,y2)+distance(x2,y2,x3,y3)+distance(x1,y1,x3,y3)
print("周长是:{0:0.2f}").format(perim)
else:
print("Kindding me?This is not a triangle!")
改变参数值值的函数:
python的参数是通过值来传递的;
如果变量是可变对象(如列表或者图形对象)返回到调用程序后,该对象会呈现被修改后的状态。
示例:处理银行账户余额
def addInterest(balances,rate):
for i in range(len(balances)):
balances[i]=balances[i]*(1+rate)
def text():
amounts=[1000,105,3500,739]
rate=0.05
addInterest(amounts,rate)
print(amouts)
text()
运行结果:[1050.0,110.25,3675.0,775.95]
函数addInterest()结束时,存储在amounts中的列表存储了新的balances值,旧值在python垃圾数据回收的时候被清楚掉。