zoukankan      html  css  js  c++  java
  • 函数

    求字符串元素的个数:

    s1 = 'fjjdsvnjfvnddjvndjkvndvvn'
    count = 0
    for i in s1:
         count +=1
    print(count)         #元素个数25
    
    
     l1 = [1,2,3,4,5,6]
    count = 0
    for i in l1:
         count += 1
    print(count)
    View Code
    以上例子,重复代码较多
    可读性差
    函数初识
    函数:就是对一个代码块或者功能的封装  什么时候用 什么时候执行 函数出现的作用,避免重复代码,增加可读性
    函数名跟变量名命名规范相同
    def my_len( ): pass #函数体 def 关键字 空格 函数名 (与变量相同):英文的冒号 #(格式) 函数体 执行函数: 函数名 + () def my_len(): l1 = [1,2,3,4,5,] count = 0 for i in l1: count += 1 my_len() ------>下面不加return ,就会自动默认添加return None print(my_len()) #None
    声明一个函数,定义函数
    def yue():
        print('拿出手机')
        print('打开微信')
        print('找一个朋友')
        print('聊一聊')
        print('一起吃饭')
        print('走你~')
    yue()   #函数的调用
    特点:函数是以功能为向导的,(有目的的)
    def login():        #请登记
          pass
    def register():      #请登记,请注册
          pass
    View Code
    函数的返回值
    def login():
         print(111)
         print(222)
         return
         print(333)      #  111   222
    View Code
    return作用:1,函数中遇到return结束函数,下面代码不执行。
               2,将函数里面的值返回给函数的执行者(调用者)。
    return的四种用法;
    第一种情况:
              只有return,返回None
    第二种情况:
              return      None   返回None
    第三种情况:
             return  单个值(返回值与单个值的类型相同)
    第四种情况:
              return多个值   以元组的形式返回给函数的调用者。
    def login():
          print(111)
          print(222)
          return  666
    print(login())
    View Code
    单个值例子:
    1,def login():
          a = 2
          b = 3
          return  a
    
    print(login())     # 2   return返回的是什么打印出来的就是什么。
    2,def login():
             a = 2
             b = 3
             return[1,2]           #[1,2]  是个列表
    
    
    print(login(),type(login())
    3.,def login():
             a = 2
             b = 3
             return[1,2]
        ret = login()
        print(ret)         #[1,2]
    4.def login():
             a = 2
             b = 3
             return[1,2]
         ret = login()
          a,b = ret
         print(a,b)              #  1   2 
    View Code
    多个值例子:元组
    def login():
          a = 2
           b = 3
           return 1, 'alex' , [ 1,2 ] , { 'name' : '老男孩' }
    ret = login()
    print()  #(1, ;alex', [1,2] , { 'name' : '老男孩‘ })
    
     2.def my_len():
             l1= [1,2,3,4,5,6]
             count = 0
             for i in l1:
                   count += 1
             return count
     print(my_len())         #6
    View Code
    什么是None ?
    所有的空集合,空列表,空字典....------->None
    
    

    参数:函数在访问的时候,给函数传递的一些信息,参数写下小括号里面
    形参:在函数声明的位置给出的变量的声明,形式参数
    实参:在函数调用的时候,给函数传递的具体的值,实际参数

    实参角度

      位置参数:按顺序一一对应,实参形参数量相等

       关键字参数:一一对应,实参形参数量相等,实参顺序可变
       混合参数:(位置参数,关键字参数)关键字参数必须在位置参数后面。
    形参角度
        位置参数:一一对应,实参形参数量相等
        默认参数:默认参数必须放在形参的位置参数后面。
           默认参数不传值则为默认值,传值则覆盖默认值。
        动态参数:
    位置参数:按照位置把实参赋值给形参
    关键字参数:对照形参,给每个参数赋值
    混合参数:位置参数,关键字参数混合用
    传参顺序:必须先写位置参数,在写关键字参数

    默认值参数必须在位置参数后面,当调用的地方不给值的时候,会使用默认值
    当出现很多重复参数的时候,考虑使用默认参数

     
    def my_len(a):   #形式参数,形参
          count = 0
          for i in l1:
               count += 1
          return count
    l1 = [1,2,3,1,6,9,100]
    s1 = 'fjnsjfsngfskgfg'
    print(my_len(l1) )   #实际参数,实参
    print(my_len(s1))      #实际参数,实参
    s1 = 'fjnsjfsngfskgfg'
    len(s1)
    View Code
    def tes (a,b,c):
          print(111)
          print(a,b,c)
    tes(22,  'alex' ,  [11,22,33])
    View Code
    比较大小:
    def max(x, y):
          if x > y:
               return x
          else:
               return y
    print(max(3000,200))
    View Code
    三元运算;(比较大小)
    1,def max(x , y): return x if x > y else y
    2,def max(x, y):
                c = x if x > y else y
                return c
    3.def max(x , y):
             return x if x > y else y
    4.c = x if x > y else y
    print(c)
    View Code
    按位置传参:
    def func(x,y):
    Pass
    func(‘a’,’b’)
    View Code
    按关键字传参;
    def func(x ,y):
          print(x , y)
    func(y=3333, x=4)
    View Code
    混合传参:
    def func1(x,y,z):
          print(x,y,z)
    func1(111,222,z=555)    #混合传参,位置参数必须在前面。
    View Code
    形参例子:
    def func2(y, x):
          print(x ,y )
    func2(1,2)         #   2  1
    View Code
    默认参数例子:默认参数可覆盖。
    def func2(y, x, z=100);
          print(x, y, z)
    func2(1,2)
    View Code
    可覆盖:
    def func2(y, x, z=100);
          print(x, y, z)
    func2(1,23000,)  #(1,2,3000)
    View Code
    
    
    练习:
    1,用函数添加员工信息;
    def input_information(name, sex=''):
        with open('information',encoding='utf-8', mode='a') as f1:
            f1.write('{}	{}
    '.format(name, sex))
    
    while True:
        msg = input('请输入用户的姓名,性别Q或者q退出').strip()
        if msg.upper() == 'Q':break
        if ',' in msg:
            name1, sex1 = msg.split(',')
            input_information(name1, sex1)
        else:
            input_information(msg)
    View Code
    2,购物车
    功能要求:
    要求用户输入总资产,例如:2000
    显示商品列表,让用户根据序号选择商品,
    '''
    1, 电脑 , 1999
    2,鼠标
    3,游艇
    '''
    加入购物车
    购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
    goods = [{"name": "电脑", "price": 1999},
             {"name": "鼠标", "price": 10},
             {"name": "游艇", "price": 20},
             {"name": "美女", "price": 998},
    ]
    
    shopping_car = []
    '''
    shopping_car = {
        0:{"name": "电脑", "price": 1999,'amount':0},
        1:{"name": "鼠标", "price": 10,'amount':0}
    }
    '''
    flag = True
    while flag:
        assets = input('请输入你的总资产:').strip()
        if assets.isdigit():
            assets = int(assets)
            print('*****商品展示*****')
            for num, goods_dic in enumerate(goods,1):
                print("{}	{}		{}".format(num, goods_dic['name'], goods_dic['price']))
            print('******************')
            while True:
                goods_num = input('请选择您要购买的商品序号/q或者Q结算:').strip()
                if goods_num.isdigit():
                    goods_num = int(goods_num)
                    if 0 < goods_num <= len(goods):
    
                        if assets >= goods[goods_num - 1]['price']:
                            assets -= goods[goods_num - 1]['price']
                            print('您已经成功购买了%s商品' % goods[goods_num - 1]['name'])
                            shopping_car.append(goods[goods_num - 1]['name'])
                        else:
                            print('您的余额不足,还剩%d钱,请及时充值' % assets)
    
                    else:
                        print('您输入的序号超出范围,请重新输入')
                elif goods_num.upper() == 'Q':
                    flag = False
                    print('您已成功购买如下商品:')
                    for i in shopping_car:
                        print(i)
                    break
    
                else:
                    print('您输入的有非数字,请重新输入')
        else:
            print('您输入的有非数字,请重新输入')
    普通版购物车
    goods = [{"name": "电脑", "price": 1999},
             {"name": "鼠标", "price": 10},
             {"name": "游艇", "price": 20},
             {"name": "美女", "price": 998},
    ]
    
    shopping_car = {}
    '''
    shopping_car = {
        0:{"name": "电脑", "price": 1999,'amount':0},
        1:{"name": "鼠标", "price": 10,'amount':0}
    }
    '''
    flag = True
    while flag:
        assets = input('33[1;35;0m请输入你的总资产:33[0m').strip()
        if assets.isdigit():
            assets = int(assets)
            origal_assets = assets
            print('*****商品展示*****')
            for num, goods_dic in enumerate(goods,1):
                print("{}	{}		{}".format(num, goods_dic['name'], goods_dic['price']))
            print('******************')
            while True:
                goods_num = input('请选择您要购买的商品序号/q或者Q结算:').strip()
                if goods_num.isdigit():
                    goods_num = int(goods_num)
                    if 0 < goods_num <= len(goods):
    
                        if assets >= goods[goods_num - 1]['price']:
                            assets -= goods[goods_num - 1]['price']
                            print('您已经成功购买了%s商品' % goods[goods_num - 1]['name'])
                            if (goods_num - 1) in shopping_car:
                                shopping_car[goods_num - 1]['amount'] += 1
                            else:
                                shopping_car[goods_num - 1] = {
                                    "name": goods[goods_num - 1]['name'],
                                    "price": goods[goods_num - 1]['price'],
                                    'amount': 1,
                                }
                        else:
                            print('您的余额不足,还剩%d钱,请及时充值' % assets)
    
                    else:
                        print('您输入的序号超出范围,请重新输入')
                elif goods_num.upper() == 'Q':
                    flag = False
                    print('您已成功购买如下商品:')
                    for i in shopping_car:
                        print('序号:{},商品名称:{},商品单价:{},购买数量:{}'.
                              format(i+1,
                                     shopping_car[i]['name'],
                                     shopping_car[i]['price'],
                                     shopping_car[i]['amount']))
                    print('此次购物消费%s元,还剩%s元' % (origal_assets-assets, assets))
                    break
    
                else:
                    print('您输入的有非数字,请重新输入')
        else:
            print('您输入的有非数字,请重新输入')
    
    # print('33[1;35;0m字体变色,但无背景色 33[0m')  # 有高亮 或者 print('33[1;35m字体有色,但无背景色 33[0m')
    # print('33[1;45m 字体不变色,有背景色 33[0m')  # 有高亮
    # print('33[1;35;46m 字体有色,且有背景色 33[0m')  # 有高亮
    # print('33[0;35;46m 字体有色,且有背景色 33[0m')  # 无高亮
    豪华版购物车
     
  • 相关阅读:
    关于session的记录
    关于<input type="hidden"/>标签的记录
    H3C S5120V2-SI 交换机配置
    Windows 系列GVLK密钥
    给因特尔S2600CO服务器主板安装【SAS控制器】驱动
    EMQ消息队列初体验
    泰国佛历的换算问题
    linux下批量查找UTF-8的BOM文件,并去除BOM
    菲律宾Globe/TM卡最省钱的上网方案
    Windows计划任务实现MYSQL冷备份
  • 原文地址:https://www.cnblogs.com/ls13691357174/p/9096544.html
Copyright © 2011-2022 走看看