(北京理工嵩天)Python学习 第五周

从本周开始,本人将只写小标题与代码,通过代码来演示知识点,避免繁琐。

函数与递归

理解函数设计作用
理解python中函数的调用和参数传递
掌握使用韩束减少代码重复性、增加程序模块化的方法
理解递归并使用

函数定义

使用def语句定义函数
def与函数名中有空格,右圆括号后需加:号
def ():

parameters(参数)多个时用逗号分隔

def add1(x):
    x=x+1
    return x    #return语句:结束函数调用并返还结果,可出现在函数任意位置

>>> add1(3)
4
>>> 

ToLucia I love U 实例

def love():
    print("I love u!")
def ToLucia():
    love()
    love()
    print("I love u forever, dear Lucia!")
    love()

>>> 
================ RESTART: E:\Python\代码目录\To Lucia I love u.py ================
>>> ToLucia()
I love u!
I love u!
I love u forever, dear Lucia!
I love u!
>>> 

改进版
Bei love Lucia & Lucia love Bei

def love():
    print("I love U !")

def loveU(name):
    print("TO" ,name)   #name变量要与语句用逗号隔开
    love()
    love()
    print("I love u so much , dear", name + "!")
    love()

def loveeachother():
    loveU("Lucia")  #name 赋值要加 “”
    print()       #空格行
    loveU("Beibei")


>>> 
================= RESTART: E:/Python/代码目录/love eachother.py =================
>>> loveeachother()
TO Lucia
I love U !
I love U !
I love u so much , dear Lucia!
I love U !

TO Beibei
I love U !
I love U !
I love u so much , dear Beibei!
I love U !
>>> 

改变参数值的函数

14银行账户计算利率——账户余额计算利息的函数

# addinterest.py
def addInterest(balance,rate):
    newBalance=balance*(1+rate)
    return newBalance
def test():
    amount=1000
    rate=0.05
    amount=addInterest(amount,rate)
    print(amount)
test

>>> 
====================== RESTART: E:/Python/代码目录/利率计算.py ======================
>>> test()
1050.0
>>> 

函数和程序结构

def createTable(principal,apr):
    #为每一年绘制星号的增长图
    for year in range(1,11):
        principal=principal*(1+apr)
        print("%2d"%year,end='')
        total=caculateNum(principal)
        print("*"*total)
    print("0.0k  2.5k  5.0k  7.5k  10.0k")
def caculateNum(principal):
    #计算星号数量
    total=int(principal*4/1000.0)
    return total
def main():
    print("This program plots the growth of a 10—year investment.")
    # 输入本金和利率
    principal = eval(input("Enter the initial principal:"))
    apr=eval(input("Enter the annualized interest rate:"))
    # 建立图表
    createTable(principal,apr)
main()
>>> 
=================== RESTART: E:/Python/代码目录/绘制银行账户增长数据图.py ===================
This program plots the growth of a 10—year investment.
Enter the initial principal:1000
Enter the annualized interest rate:0.2
 1****
 2*****
 3******
 4********
 5*********
 6***********
 7**************
 8*****************
 9********************
10************************
0.0k  2.5k  5.0k  7.5k  10.0k
>>> 

递归函数

递归:使用函数自身的方法如
在这里插入图片描述

函数实例

绘制树思路:
1.图形绘制指令
2.数绘制算法
在这里插入图片描述

import turtle
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(30,0)
    #Return the TurtleScreen object the turtle is drawing on.
    #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(x,y)#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],110,65,0.6375)
main()

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 turle 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)

(无法运行,求大神。。。。)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值