1.函数定义
完成特定功能的一个语句组,函数可以反馈结果
为函数提供不同的参数,可以实现对不同数据的处理。
自定义函数、系统自带函数(python内嵌函数,标准库函数、图形库)
使用函数的目的:降低编程的难度、代码重用
函数定义:def语句。def (<参数>):
形式参数、实际参数
函数调用:(<参数>)
return语句:结束函数调用,并将结果返回给调用者。
#打印生日快乐
def happy():
print("happy birthday to you !")
def main(str1):
happy()
happy()
print("happy birthday to"+"dear "+str1)
happy()
main("mike")
2.函数调用和返回值
无返回值:return None
返回值可以是变量和表达式,可以返回一个或多个。
#两点间距离
import math
def distance(x1,x2,y1,y2):
a=(x1-x2)*(x1-x2)
b=(y1-y2)*(y1-y2)
dist=math.sqrt(a+b)
return dist
def main():
x1,y1,x2,y2=eval(input())
distance(x1,x2,y1,y2)
print("distance=",distance(x1,x2,y1,y2))
main()
#三角形周长
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("输入三个点的坐标:")
x1,y1=eval(input())
x2,y2=eval(input())
x3,y3=eval(input())
if(isTriangle(x1,y1,x2,y2,x3,y3)):
perim=distance(x1,y1,x2,y2)+distance(x2,y2,x3,y3)+distance(x1,y1,x3,y3)
else :
print("wrong!")
main()
3.改变参数的函数值
#银行利率计算
def addInterest(balance,rate):
newBalance=balance*(1+rate)
return newBalance
#balance=newBalance
def main():
amount=1000
rate=0.05
amount=addInterest(amount,rate)
print(amount)
main()
#多个银行账户的程序利率计算
def addInterest(balance,rate):
for i in range(len(balances))
balance[i]=balance[i]*(1+rate)
def main():
amounts=[1000,105,3500,739]
rate=0.05
addInterest(amounts,rate)
print(amounts)
main()
4.函数程序结构与递归
def createTable(principle,apr):
#为每一年绘制星号的增长图
for year in range(1,11):
principle=principle*(1+apr)
print("%2d"%year,end='')
total=caculateNum(principle)
print("*"*total)
print(" 0.0K 2.5K 5.0K 7.5K 10.0K")
def caculateNum(principle):
#计算星号数量
total=int(principle*4/1000.0)
return total
def main():
print("This program plots the growth of a 10-year investment")
#输入本金和利率
principle=eval(input("enter the initial principal: "))
apr=eval(input("enter the rate:"))
#建立图表
createTable(principle,apr)
main()
递归计算
#递归
def fact(n):
if n==0:
return 1
else :
return n*fact(n-1)
def main():
print(fact(3))
main()
#字符串反转
def reverse(s):
if s=="":
return s
else :
return reverse(s[1:])+s[0]
def main():
print(reverse("ajdifjoi"))
main()
5.函数实例分析
# drawtree.py
from turtle import Turtle, mainloop
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 5: #
lst = []
for p in plist:
p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
p.left(a) #Turn turtle left by angle units
q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
lst.append(p)#将元素增加到列表的最后
lst.append(q)
tree(lst, l*f, a, f)
def main():
p = Turtle()
p.color("green")
p.pensize(5)
#p.setundobuffer(None)
p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
#because hiding the turtle speeds up the drawing observably.
#p.speed(10)
# p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
p.speed(10)
#TurtleScreen methods can then be called for that object.
p.left(90)# Turn turtle left by angle units. direction 调整画笔
p.penup() #Pull the pen up – no drawing when moving.
p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
#否则turtle一移动就会自动的把线画出来
#t = tree([p], 200, 65, 0.6375)
t = tree([p], 200, 65, 0.6375)
main()