一、函数
1、函数定义
def 函数名(参数列表):
<body>
2、返回值 return
返回值可以有多个
##多个返回值 def sumDiff(x,y): return x+y,x-y n1,n2 = eval(input('输入两个数:')) s,d = sumDiff(n1,n2) print('和为{},差为{}'.format(s,d))
##计算三角形周长 import math def square(x): return x*x #计算两点之间的距离 def distance(x1,x2,y1,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('输入三个坐标点(x,y):') x1,y1 = eval(input('坐标点1(x1,y1)=')) x2, y2 = eval(input('坐标点2(x2,y2)=')) x3, y3 = eval(input('坐标点3(x3,y3)=')) #判断三个点是否构成三角形 if(isTriangle(x1,y1,x2,y2,x3,y3)): ##计算三角形周长 perim = distance(x1,y1,x2,y2)+distance(x2,y2,x3,y3)+distance(x3,y3,x1,y1) print('该三角形周长为:{:.2f}'.format(perim)) else: print('三个点无法构成三角形') main()
3、参数
如果变量是可变对象【列表】,返回到调用程序后,对象会呈现被修改后的状态
def addInterest(balances,rate): for i in range(len(balances)): balances[i] = balances[i] * (1+rate) def test(): amounts = [1000,500,1200,789] rate = 0.05 addInterest(amounts,rate) print(amounts) test() ##[1050.0, 525.0, 1260.0, 828.45]