zoukankan      html  css  js  c++  java
  • class 2-1 小项目练习

    一.汇率计算

    其中涉及到(字符串转化数字eval,pass为占位符,切片等知识点)

    单步调试,点击断点处,右击选择debug

    USD_VS_RMB = 6.77
    currency_str_value= input("请输入带单位的货币金额(退出输入Q):")
    i = 0
    while currency_str_value != 'Q':
        i += 1
        print("循环次数", i)
        #h获取货币单位
        unit = currency_str_value[-3:]
        if unit = 'CNY':
            rmb_str_value = currency_str_value[:-3]
            #将字符串转换为数字eval
            rmb_value = eval(rmb_str_value)
            usd_value = rmb_value / USD_VS_RMB
            print("美元(USD)金额:",usd_value)
        elif unit == 'USD':
            usd_str_value = currency_str_value[:-3]
            usd_value = eval(usd_str_value)
            rmb_value = usd_value*USD_VS_RMB
        else:
            print("目前版本暂时不支持该种货币!")
        print("*******************************************************")
        currency_str_value= input("请输入带单位的货币金额(退出输入Q):")

    2.函数

    <1>.函数定义

    def <函数名> (<参数列表>):

      <函数体>

      return<返回值列表>

    <2>.调用过程

    • 调用程序在调用函数处暂停执行
    • 调用时将参数(实参)赋值给函数的参数(形参)
    • 执行函数体
    • 返回函数结果,回到调用处继续执行

    <3>.(1)函数调用运行流程结构化

    def convert_currency(im, er):
        """汇率兑换"""
        out = im * er
        return out
    
    def main():
        """主函数"""
        USD_VS_RMB = 6.77
        currency_str_value = input("请输入带单位的货币金额: ")
        unit = currency_str_value[-3:]
        if unit == 'RMB':
            exchange_rate = 1/USD_VS_RMB
        elif unit== 'USD':
            exchange_rate = USD_VS_RMB
        else:
            exchange_rate = -1
    
        if exchange_rate != -1:
            in_money = eval(currency_str_value[:-3])
            #调用函数
            out_money = convert_currency(in_money,exchange_rate)
            print("转化后的金额:",out_money)
        else:
            print("不支持该种货币")
    
    if __name__ == '__main__':
        main()

    (2)简单的函数定义

    lambda函数(匿名函数)

    • 特殊函数——匿名函数
    • 使用方法:<函数名> = lambda<参数列表>:<表达式>
    • 用于简单的,能够在一行内表示的函数,计算结果为返回值(表达式时没有return关键字)
    def main():
        """主函数"""
        USD_VS_RMB = 6.77
        currency_str_value = input("请输入带单位的货币金额: ")
        unit = currency_str_value[-3:]
        if unit == 'RMB':
            exchange_rate = 1/USD_VS_RMB
        elif unit== 'USD':
            exchange_rate = USD_VS_RMB
        else:
            exchange_rate = -1
    
        if exchange_rate != -1:
            in_money = eval(currency_str_value[:-3])
            #使用lambda定义函数
            convert_currency2 = lambda x: x * exchange_rate  #表达式结果直接返回,没有return关键字
            #调用lambda函数
            out_money = convert_currency2(in_money)
            print("转化后的金额:",out_money)
        else:
            print("不支持该种货币")
    
    if __name__ == '__main__':
        main()

    二.分型树绘制

    绘制使用到turtle库

    与之前的程序区别

    • 没有显示input()与output()
    • 没有赋值语句
    • 大部分语句为<a>.<b>()的形式
    1. 表示使用<a>中的方法<b>()
    2. 调用函数库<a>中的函数<b>()

    turtle.forward(distance):画笔向前移动distance距离

    turtle.backward(distance):画笔向后一定distance距离

    turtle.right(degree):画笔向右旋转degree度

    turtle.penup():抬起画笔,之后移动不绘制形状

    turtle.pendown():落下画笔,之后移动绘制形状

    turtle.pensize():设置画笔宽度

    turtle.pencolor(whilte/black/grey...):设置画笔颜色

    turtle.exitonclick():点击关闭图形窗口(如果缺失,图形窗口一闪而过)

    https://docs.python.org/3.0/library/turtle.html

    绘制五角星

    import turtle
    
    def drawgram(size):
        i = 1
        while i<=5:
            turtle.forward(size)
            turtle.right(144)
            i += 1
    
    def main():
        "主函数"
        size =50
        while size <=100:
            drawgram(size)
            size += 20
    
        turtle.exitonclick()
    
    if __name__ == '__main__':
        main()

     递归函数:函数调用自身的方式

    import turtle
    
    def drawgram(size):
        i = 1
        while i<=5:
            turtle.forward(size)
            turtle.right(144)
            i += 1
        #五角星绘制完成,更新参数
        size += 10
        if size <=100:
            drawgram(size)
    
    def main():
        turtle.penup()
        turtle.backward(100)
        turtle.pendown()
      
        size = 50
        drawgram(size)
        turtle.exitonclick()
    
    if __name__ == '__main__':
        main()

    绘制树状图

    import turtle
    
    def draw_branch(size):
        """绘制分型树"""
        if size > 5:
            if (size - 5) <= 10:
                turtle.pencolor('green')
            else:
                turtle.pencolor('brown')
            #绘制右侧树枝,需先落下笔绘制
            turtle.pendown() 
            turtle.forward(size)
            turtle.right(20)
            draw_branch(size - 5)
            #绘制左侧树枝
            turtle.left(40)
            draw_branch(size - 5)
            #返回之前的树枝,为防止覆盖颜色返回需要抬起笔,相应之前要落下笔
            turtle.penup()
            turtle.right(20)
            turtle.backward(size)
    
    def main():
        """主函数"""
        turtle.left(90)
        draw_branch(40)
        turtle.exitonclick()
    
    if __name__ == '__main__':
        main()

    三. BMR(basal Metabolic Rate:基础代谢率)计算

    BMR(男) =(13.7*体重(KG))+ (5.0*身高(cm)) - (6.8*年龄))+66

    BMR(女) =(9.6*体重(KG))+ (1.8*身高(cm)) - (4.7*年龄))+655

    数值类型:

    • 整数类型,int()
    • 浮点数类型,float()

    类型转换

    • 整数->浮点数,float(4) -> 4.0
    • 浮点数->整数, int(3.14) -> 3, 只会保留整数部分
    • 字符串->整数, 字符串 -> 浮点数, int('3') -> 3, float('3.14') -> 3.14
    • 判断类型: type()函数

    字符串操作补充

    • 字符串分割(规律性的字符分割):str.split()   https://docs.python.org/3/library/stdtypes.html#str.split
    • 字符串格式化输出,使用{ }占位    str.format()

        例如:‘{ }公斤,{ }厘米’. format(70, 175)  其中format后面的70对应前面的第0个位置的数字,175对应前面的第一个位置数字

        重复输出时可以使用数字标记顺序

        ‘{0}公斤,{1}厘米’.format(70,175)

    异常处理机制:

          语法:

    • try:

        <body>   当python遇到try语句,先尝试执行try包含的代码块,

    • except<ErrorType1>:

        <handler1>  如果没有错误发生,执行try-except后面语句

    • except<ErrorType2>:

        <handler2>  如果发生错误,python寻找一个复核人该错误的异常语句然后执行相应的except处理代码

    • except:

        <handler0>

    def main():
        judge = input('是否退出程序(Y/N):')
        while judge != 'Y':
            # gender = str(input('性别: '))
            # weight = float(input('体重(KG): '))
            # height = float(input('身高(cm): '))
            # age = int(input('年龄: '))
            print('请输入以下信息,用空格分割')
            input_str = input('性别 体重(KG) 身高(cm) 年龄: ')
            str_list = input_str.split(' ')
            try:
                gender = str_list[0]
                weight = float(str_list[1])
                height = float(str_list[2])
                age = int(str_list[3])
    
                if gender == '':
                    BMR =(13.7 * weight)+ (5.0 * height) - (6.8 * age)+ 66
                elif gender =='':
                    BMR =(9.6 * weight) + (1.8 * height) - (4.7 * age)+ 655
                else:
                    BMR = -1
    
                if BMR != -1:
                    print('性别:{}, 体重:{}公斤,身高:{}厘米, 年龄:{}岁'.format(gender,weight,height,age))
                    print('基础代谢率:{}大卡'.format(BMR))
                else:
                    print('暂不支持该性别')
            except ValueError:
                print('请输入正确信息!')
            except IndexError:
                print('输入的信息过少!')
            except:
                print('程序异常!')
    
            judge = input('是否退出程序(Y/N):')
    
    if __name__ == '__main__':
        main()

     四. 52周存钱(阶梯存钱)

    • 列表(list)时有序的元素集合
    • 可通过索引访问单个元素,如 l[2],l[-1]
    • 可通过区间索引访问子列表内容,如 l[2:5], l[-3:] 
    • 列表中每个元素类型可以不同

    列表操作符(列表可放置不同数据类型)

    • list1 + list2 :合并(链接)两个列表
    • list1 n   :重复n次列表内容
    • len( list1):返回列表长度(元素个数)
    • x in list1 :检查元素是否在列表中
    • list1.append(X) :将x添加到列表末尾
    • list1.sort() :对列表元素进行排序
    • list1.reverse() :将列表元素逆序
    • list1.index(x) :返回第一次出现元素x的索引值 ,即该元素位置
    • list1.insert(i,x)  : 在位置i 处插入新元素x
    • list1.count(x) : 返回元素 x 在列表中的数量
    • list1.remove(x) : 删除列表中第一次出现的元素x
    • list1.pop(i) : 取出列表中i 位置上的元素,并将其删除

    math 库介绍及使用:参考 https://doc.python.org/3/library/math.html

    • math.pi :圆周率
    • math.ceil(x) :对x向上取整 ,例:math.ceil(2.2) ,输出3
    • math.floor(x) :对x 向下取整
    • math.pow(x, y) : x的y次方
    • math.sqrt(x) : x 的平方根
    • math.fsum(list1) : 对集合内的元素求和

    for 循环

    • 使用for语句可以循环遍历整个系列的内容

        for <x> in <list1>:

          body

    • 循环变量x在每次循环时,被赋值成对应的元素内容
    • 与while循环区别
      • for 循环的次数固定,即所遍历的序列长度
      • while为无限循环
    • range(n)返回一个可迭代的对象
      • list(range(n))将迭代类型转换为列表类型(从0开始计数到 n-1)

    函数的传递:

    • 函数通过参数与调用程序传递信息
    • 变量的作用范围
      • 局部,函数内的变量作用范围只在函数内
      • 全局,写在函数外的变量,在所有函数中都能使用(使用global声明)
    • 函数的形参只接受实参的值,给形参赋值并不影响实参

    datetime 库

    •  处理事件的标准函数库datetime
    • datetime.now() 获取当前日期和时间
    • 字符串 ——> dateime
      • datetime.strptime()  解析时间和字符串
    • datetime ——> 字符串
      • datetime.strftime()格式化datetime为字符串显示  https:\docs.python.org3library/datetime.html#strftime-strptime-behavior
    • isocalendar() 返回年,周数,及周几
      • https://docs.python.org/3/library/datetime.html#module-datetime
    import math
    import datetime
    #saving = 0  #全局变量
    def save_money_in_n_week(money_per_week, increase_money,total_week,):
        #global saving   #声明saving为全局变量
        money_list = []
        saved_money_list = []
        for i in range(total_week):   #如果没有参数外部参数传入,此类total_week的实参将会报错,需要将其形参定义入函数
            money_list.append(money_per_week)
            saving = math.fsum(money_list)
            saved_money_list.append(saving)
            #print('第{}周,存入{}元,账户累计{}元'.format(i + 1, money_per_week, saving))
            money_per_week += increase_money
            #print("函数内saving:",saving)
        return saved_money_list #返回得出的值,供外部调用
    
    def main():
        money_per_week = float(input('请输入每周存入金额:'))
        increase_money = float(input('请输入你要存钱递增的额度:'))
        total_week = int(input('请输入你要存钱的周数:'))
    
        #saving = 0  #局部变量
        #函数调用
        saved_money_list = save_money_in_n_week(money_per_week,increase_money,total_week)
        input_date_str = input('请输入日期(yyyy/mm/dd): ')
        input_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d')   #不要忘记‘/’,正确格式为%Y/%m/%d
        week_num = input_date.isocalendar()[1]
        print('第{}周的存款:{}元'.format(week_num, saved_money_list[week_num - 1]))
    
    if  __name__ == '__main__':
        main()
  • 相关阅读:
    angular 项目创建
    博客园 样式记录
    postman运行后窗口不显示的解决办法 --转载
    关于Vue中this作用域说明,以及一个this->undefined问题的处理 --转载
    vue 中 使用 vue-cookie --转载
    某些时候 v-if 会导致 v-modal 内部数据获取不到 也watch不到,这个时候用v-show即可,另外提一下数组要整体赋值才有双向绑定--转载
    CSS 基础4
    CSS 基础3
    CSS 基础1
    CSS 基础2
  • 原文地址:https://www.cnblogs.com/Mack-Yang/p/9742310.html
Copyright © 2011-2022 走看看