8.每日知识归类之第八天综合(函数介绍 )

--------------------------------------------day 8---------------------------------------------

 

一、上节课复习:

    什么是文件?

        文件是操作系统提供给应用程序操作硬盘的的一个虚拟单位,

        用于应用程序将数据永久保存

 

    文件的打开模式:

        t:text文本模式,读写文件是以字符串为单位,需要指定字符编码,

            t模式的局限性是只能读写文本文件

        b:bytes字节模式,读写文件都是以bytes为单位,不需要指定字符编码

           b模式的好处的是可以读写任意类型的文件

 

        f=open(r'a\b\a.txt',mode='wb') #linux, mac系统中路径起点/表示一个文件夹

        f.write('你好'.encode('utf-8'))

        f.close()

 

    注意:

        t或b都不能单独使用

        必须与r、w、a模式组合使用

 

     强调:

        写文件换行符用\n

        读文件换行符也是\n

 

二、作业讲解之三级菜单 (两种方法)

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}

# 方法一:
# tag=True
# while tag:
#     menu1=menu
#     for key in menu1:
#         print(key)
#
#     choice1=input('第一层>>: ').strip() # choice1='asdfkhsadjkfhsakdfja'
#     if choice1 == 'b':break
#     if choice1 == 'q':
#         tag = False
#         break
#     if choice1 not in menu1:continue
#
#     while tag:
#         menu2=menu1[choice1] #menu1['北京']
#         for key in menu2:
#             print(key)
#
#         choice2 = input('第二层>>: ').strip()
#         if choice2 == 'b':break
#         if choice2 == 'q':
#             tag=False
#             break
#         if choice2 not in menu2:continue
#
#         while tag:
#             menu3 = menu2[choice2]  #
#             for key in menu3:
#                 print(key)
#
#             choice3 = input('第三层>>: ').strip()  # choice3='五道口'
#             if choice3 == 'b':break
#             if choice3 == 'q':
#                 tag=False
#                 break
#             if choice3 not in menu3: continue
#
#             while tag:
#                 menu4 = menu3[choice3]  #
#                 for key in menu4:
#                     print(key)
#
#                 choice4 = input('第四层>>: ').strip()  # choice1='北京'
#                 if choice4 == 'b':break
#                 if choice4 == 'q':
#                     tag=False
#                     break
#
#                 if choice4 not in menu4: continue

#方法二:

#逻辑分析:
#1、拿到当前层的菜单字典
#2、循环打印字典的key
#3、接收用户输入
#4、进入下一层,需要先拿到下一次层的字典

layers=[menu,]
while True:
    if len(layers) == 0:break
   
# 1、拿到当前层的菜单字典
   
current_layer=layers[-1]
    # 2、循环打印字典的key
   
for key  in current_layer:
        print(key)
    # 3、接收用户输入
   
choice=input('>>: ').strip()
    if choice == 'q':break
    if
choice == 'b':
        layers.pop(-1)
        continue
    if
choice not in current_layer:continue
   
# 4、进入下一层,需要先拿到下一次层的字典
   
layers.append(current_layer[choice])

 

三、作业讲解之购物车(常规,函数)

import os

 

product_list = [['Iphone7',5800],

                ['Coffee',30],

                ['疙瘩汤',10],

                ['Python Book',99],

                ['Bike',199],

                ['ViVo X9',2499],

 

                ]

 

shopping_cart={}

current_userinfo=[]

 

db_file=r'db.txt'

 

while True:

    print('''

    1 登陆

    2 注册

    3 购物

    ''')

 

    choice=input('>>: ').strip()

 

    if choice == '1':

        #1、登陆

        tag=True

        count=0

        while tag:

            if count == 3:

                print('\033[45m尝试次数过多,退出。。。\033[0m')

                break

            uname = input('用户名:').strip()

            pwd = input('密码:').strip()

 

            with open(db_file,'r',encoding='utf-8') as f:

                for line in f:

                    line=line.strip('\n')

                    user_info=line.split(',')

 

                    uname_of_db=user_info[0]

                    pwd_of_db=user_info[1]

                    balance_of_db=int(user_info[2])

 

                    if uname == uname_of_db and pwd == pwd_of_db:

                        print('\033[48m登陆成功\033[0m')

 

                        # 登陆成功则将用户名和余额添加到列表

                        current_userinfo=[uname_of_db,balance_of_db]

                        print('用户信息为:',current_userinfo)

                        tag=False

                        break

                else:

                    print('\033[47m用户名或密码错误\033[0m')

                    count+=1

 

    elif choice == '2':

        uname=input('请输入用户名:').strip()

        while True:

            pwd1=input('请输入密码:').strip()

            pwd2=input('再次确认密码:').strip()

            if pwd2 == pwd1:

                break

            else:

                print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')

 

        balance=input('请输入充值金额:').strip()

 

        with open(db_file,'a',encoding='utf-8') as f:

            f.write('%s,%s,%s\n' %(uname,pwd1,balance))

 

    elif choice == '3':

        if len(current_userinfo) == 0:

            print('\033[49m请先登陆...\033[0m')

        else:

            #登陆成功后,开始购物

            uname_of_db=current_userinfo[0]

            balance_of_db=current_userinfo[1]

 

            print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(

                uname_of_db,

                balance_of_db

            ))

 

            tag=True

            while tag:

                for index,product in enumerate(product_list):

                    print(index,product)

                choice=input('输入商品编号购物,输入q退出>>: ').strip()

                if choice.isdigit():

                    choice=int(choice)

                    if choice < 0 or choice >= len(product_list):continue

 

                    pname=product_list[choice][0]

                    pprice=product_list[choice][1]

                    if balance_of_db > pprice:

                        if pname in shopping_cart: # 原来已经购买过

                            shopping_cart[pname]['count']+=1

                        else:

                            shopping_cart[pname]={'pprice':pprice,'count':1}

 

                        balance_of_db-=pprice # 扣钱

                        current_userinfo[1]=balance_of_db # 更新用户余额

                        print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db))

 

                    else:

                        print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(

                            price=pprice,

                            lack_price=(pprice - balance_of_db)

                        ))

                    print(shopping_cart)

                elif choice == 'q':

                    print("""

                    ---------------------------------已购买商品列表--------

                    id          商品        数量         单价         总价

                    """)

 

                    total_cost=0

                    for i,key in enumerate(shopping_cart):

                        print('%22s%18s%18s%18s%18s' %(

                            i,

                            key,

                            shopping_cart[key]['count'],

                            shopping_cart[key]['pprice'],

                            shopping_cart[key]['pprice'] * shopping_cart[key]['count']

                        ))

                        total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count']

 

                    print("""

                    您的总花费为: %s

                    您的余额为: %s

                    ----------------------------end------------------------

                    """ %(total_cost,balance_of_db))

 

                    while tag:

                        inp=input('确认购买(yes/no?)>>: ').strip()

                        if inp not in ['Y','N','y','n','yes','no']:continue

                        if inp in ['Y','y','yes']:

                            # 将余额写入文件

 

                            src_file=db_file

                            dst_file=r'%s.swap' %db_file

                            with open(src_file,'r',encoding='utf-8') as read_f,\

                                open(dst_file,'w',encoding='utf-8') as write_f:

                                for line in read_f:

                                    if line.startswith(uname_of_db):

                                        l=line.strip('\n').split(',')

                                        l[-1]=str(balance_of_db)

                                        line=','.join(l)+'\n'

 

                                    write_f.write(line)

                            os.remove(src_file)

                            os.rename(dst_file,src_file)

 

                            print('购买成功,请耐心等待发货')

 

                        shopping_cart={}

                        current_userinfo=[]

                        tag=False

 

 

                else:

                    print('输入非法')

 

 

    else:

        print('\033[33m非法操作\033[0m']

 

四、函数介绍

1、为什么要有函数?什么是函数?
    a. 组织结构不清晰,可读性差
    b. 代码冗余
    c. 管理维护的难度极大,扩展性差

    具备某一个功能的工具就是程序的中函数 #‘函数即变量’
    事先准备工具的过程----》函数的定义
    拿来就用----》函数的调用

    所以函数的使用必须遵循:先定义,再调用

 

五、定义函数

1、语法

def 函数名(参数1,参数2,...):

    """

    文档描述

    """

    代码1

    代码2

    代码3

    return 值

 

def:定义函数的关键字

函数名:是用来调用函数的,函数名的命名必须能反映出函数的功能

文档描述:推荐写上,来增强函数的可读性

代码块:函数的功能实现代码

return:函数的返回值

 

2. 定义阶段

def print_sym(sym,count): #print_sym=<function print_msg at 0x000001B2A33698C8>    #十六进制,表在内存中的位置
   
print(sym*count)
 
def print_msg(msg):
    print('\033[045m%s\033[0m' %msg]
 
3、调用阶段:函数名加括号就是在调用函数
print_sym('#',30)
print_msg('hello egon')
print_sym('#',30)

 

4、 定义函数的三种类型

a. 有参函数:参数是函数代码用来接收外部传入值的

def max2(x,y): #x=100,=y101
   
if  x > y:
        print(x)
    else:
        print(y)

   max2(100,101)

 

b. 无参参数:当函数体的代码逻辑不需要函数的调用者掺入值的情况下,就无参

#无参参数相对用的不多

def interactive():
    name=input('username>>: ').strip()
    pwd=input('password>>: ').strip()
    print(name,pwd)

    interactive() #定义时无参,意味着调用时也无须传入参数

 

c. 空函数:函数体为pass

def auth():
    """
   
这是一个认证功能
   
:return:
    """
   
pass

def
put():
    """
   
上传功能
   
:return:
    """
   
pass

def
get():
    """
   
下在功能
   
:return:
    """
   
pass

def
ls():
    """
    list contents
   
:return:
    """
   
pass
 
 
 
d. 练习
uname_of_db='egon'
pwd_of_db='123'

def interactive():
    uname_of_db=input('username: ').strip()
    pwd_of_db=input('password: ').strip()
    return uname_of_db, pwd_of_db


def auth(uname,pwd):
    if uname==uname_of_db and pwd==pwd_of_db:
        print('登陆成功')
    else:
        print('登陆失败')

res=interactive()
x=res[0]
y=res[1]
auth(x,y)
 
#函数的功能越细越好。比如,认证可分为输入和对比
 
5. 函数的调用
函数的使用必须遵循:先定义后调用的原则
注意:没事先定义函数而直接调用,就相当于引用一个不存在的变量名
定义阶段:在定义阶段只检测语法,不执行函数体代码
调用阶段:根据函数名找到函数的内存地址,然后执行函数体代码
 
运行以下代码,不报错,因为没有语法错误
def func():
   xxx
运行以下代码,报错,因为有语法错误
def func():
  print('sadfsadf'
 
运行以下代码,不报错,因为定义在调用之前,若将foo()前移,则报错
def bar():    #定义阶段
  print('from bar')
def foo():
  print('from foo')
  bar()

foo()      #调用阶段
 
6. 调用函数的三种形式
a. 语句形式:foo()
def func():
    print('from func')

func()
 
b. 表达式形式:3*len('hello')
def max2(x,y):
    if x > y:
        return x
    else:
        return y

res=max2(10,3)
print(res)
 
c. 当中另外一个函数的参数:range(len('hello'))
def max2(x,y):
    if x > y:
        return x
    else:
        return y

res=max2(max2(10,3),11)
print(res)
 
6. 函数的返回值
什么时候应该有返回值:函数体代码运行完毕后需要有一个返回结果给调用者
 
返回值的三种形式
a.      没有return,返回值为None
def func():
    pass

res=func()
print(res)
 
b.     return后跟一个值,返回该值本身
def func1():
    return 1

res=func1()
print(res)
 
c.      return可以逗号分隔,返回多个值,会返回一个元组给调用者
def func2():
    return 1,2,[1,2,3]   #等同于return (1,2,[1,2,3])

res=func2()
print(res)
 
return的注意点:
a.      return返回值的值,没有类型限制
b.     return是函数结束的标志,函数内可以写多个return,但执行一次,函数就立刻结束,并把return后的值作为本次调用的返回值
 
def func3():
    print('first')
    return 1    #return 1 然后结束
    print('second')
    return 2
    print('third')
    return 3

res=func3()
print(res)
 
posted on 2018-08-11 17:21  2Maike  阅读(114)  评论(0编辑  收藏  举报