Python零基础先修课第四周

Python零基础先修课第四周

笔记

第四周代码复用

  1. 函数定义
    -函数:完成特定功能的一个语句组,通过调用函数名来完成语句组的功能。
    -函数可以反馈结果。
    -为函数提供不同的参数,可实现对不同数据的处理。
    -自定义函数:用户自己写的
    -系统自带函数:Python内嵌的函数,Python标准库中的函数,图形库中的方法等
    -使用函数目的:降低编程难度、代码重用
    -使用def定义函数,Python不需要定义函数返回类型,能返回任何类型
def <name>(<parameters>):
<body>

-函数名<name>:任何有效的Python标识符
-参数列表<parameters>:调用函数时传递给它的值。参数个数大于等于零多个参数由逗号分隔。
-形式参数:定义函数式,函数名后面圆括号中的变量,简称“形参”。形参只在函数内部有效。
-实际参数:调用函数时,函数名后面圆括号中的变量简称“实参”。
-函数体<body>:函数被调用时执行的代码,由一个或多个语句组成。
-函数调用的一般形式:<name>(<parameters>)
-举例:

def add1(x):
    x=x+1
return x

-return语句:结束函数调用,并将结果返回给调用者。
-return语句是可选的,可出现在函数体的任意位置。
-没有return语句,函数在函数体结束位置将控制权返回给调用方。
-函数接口:返回值和参数
-函数传递信息主要途径:通过函数返回值的方式传递信息、通过参数传递信息。
2. 函数的调用和返回值
-return语句:程序退出该函数,并返回到函数被调用的地方。
-return语句返回的值传递给调用程序。
-返回只有两种形式:返回一个值、返回多个值
-无返回值的return语句等价于return None。
-None是表示没有任何东西的特殊类型
-返回值可以是一个变量,也可以是一个表达式。

def square(x):
y=x*x
return y

等价于

def squarel(x):
return x*x

应用square()函数编写程序计算两点之间的距离
在这里插入图片描述

def distance(x1,y1,x2,y2):
	dist=math.sqrt(square(x1-x2)+square(y1-y2))
	return dist

计算三角形周长:

#计算三角形的周长
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 in turn: ")
    x1,y1=eval(input("Point1:(x,y)="))
    x2,y2=eval(input("Point2:(x,y)="))
    x3,y3=eval(input("Point3:(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("The perimeter of the triangle is: {0:0.2f}".format(perim))
    else:
        print("Kdding me? This is not a triangle!")
main()
  1. 改变参数值的函数:
    银行账户计算利率——账户余额计算利息的函数
def addInterest(balance,rate):
    newBalance=balance*(1+rate)
    balance=newBalance
def main():
    amount=1000
    rate=0.05
    addInterest(amount,rate)
    print(amount)
main()

在这里插入图片描述

运行后发现amount还是1000,不是1050,这是因为函数的形参只接收了实参的值,给形参赋值并不影响实参。Python可以通过值来传递参数。
修改程序:

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

处理多个银行账户的程序
-用列表存储账户余额信息
-列表中第一个账户余额

balance[0]=balance[0]*(1+rate)
balance[1]=balance[1]*(1+rate)

代码如下:

def addInterest(balances,rate):
    for i in range(len(balances)):
        balances[i]=balances[i]*(1+rate)
def test():
    amounts=[1000,105,3500,739]
    rate=0.05
    addInterest(amounts,rate)
    print(amounts)
test()

在这里插入图片描述
Python的参数是通过值来传递的,但是如果变量是可变对象(如列表和图形对象),返回到调用程序后,该对象会呈现被修改后的状态。
4. 函数和程序结构
-函数可以简化程序,并且函数可以使程序模块化
-用函数将较长的程序分割成短小的程序段,可以方便理解

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 pricinpal: "))
    apr=eval(input("Enter the annualized interest rate: "))
    #建立图表
    createTable(principal,apr)
main()
  1. 结构与递归
    递归:函数定义中使用函数自身的方法
    经典例子:阶乘
    在这里插入图片描述

特征:有一个或多个基例是不需要再次递归的,所有的递归链都要以一个基例结尾
-递归每次调用都会引起形函数的开始
-递归有本地值的副本,包括该值的参数
-阶乘递归函数中:每次函数调用中的相关n值在中途的递归链暂时存储,并在函数返回时使用。
在这里插入图片描述

字符串反转
-Python列表有反转的内置方法
方法一:字符串转换为字符列表,反转列表,列表转换回字符串
方法二:递归
IPO模式:
输入:字符串
处理:用递归的方法反转字符串
输出:反转后的字符串

def reverse(s):
return reverse(s[1:])+s[0]

会报错,因为没有基例
-构造对函数,需要基例
-基例不进行递归,否则递归就会无限循环执行
因此:

def reverse(s):
if s=='':
    return s
else:
    return reverse(s[1:])+s[0]
  1. 实例
    树的绘制思路
    -首先学习简单图形绘制的指令
    -其次为树的绘制设计算法
    在这里插入图片描述
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, units 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(1)
    #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()

作业

作业:
1
在这里插入图片描述

在这里插入图片描述

2七段数码管的绘制

import turtle,time
def drawGap():
    turtle.penup()
    turtle.fd(5)
def drawLine(draw):     #绘制单段数码管
    drawGap()
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    drawGap()
    turtle.right(90)
def drawDigit(digit):   #根据数字绘制七段数码管
    drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,6,8] else drawLine(False)
    turtle.left(90)
    drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
    turtle.left(180)
    turtle.penup()      #为绘制后续数字确定位置
    turtle.fd(20)       #为绘制后续数字确定位置
def drawDate(date):     #获得要输出的数字 date为日期,格式为'%Y-%m=%d+'
    turtle.pencolor("red")
    for i in date:
        if i=='-':
            turtle.write('年',font=("Arial",18,"normal"))
            turtle.pencolor("green")
            turtle.fd(40)
        elif i=='=':
            turtle.write('月',font=("Arial",18,"normal"))
            turtle.pencolor("blue")
            turtle.fd(40)
        elif i=='+':
            turtle.write('日',font=("Arial",18,"normal"))
        else:
            drawDigit(eval(i))  #通过eval()函数将数字变为整数
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(5)
    drawDate(time.strftime('%Y-%m=%d+',time.gmtime()))
    turtle.hideturtle()
    turtle.done()
main()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值