Python基础-week02 Python的常用数据类型

一.模块初识

  import导入Py自带模块例如os,sys等及其自己编写的Py文件,导入到其他文件中,默认查找当前目录。如果不在同一目录,会报错,将该自定义py文件模块放到site-packages目录里,其他方法会在后面笔记中中讲解。

  Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,以后的课程中会深入讲解常用到的各种库,现在,我们先来象征性的学2个简单的:

    

 1 #sys模块
 2 import sys
 3 print(sys.argv)
 4     
 5 #os模块
 6 import os
 7 os.system("df -h") #调用系统命令
 8     
 9 import os sys
10 os.system(''.join(sys.argv[1:])) #把用户的输入的参数当作一条命令交给os.system来执行
View Code

 

 

二.pyc是什么?

  在说这个问题之前,我们先来说两个概念,PyCodeObject和pyc文件。

  

 

 

  我们在硬盘上看到的pyc自然不必多说,而其实PyCodeObject则是Python编译器真正编译成的结果。我们先简单知道就可以了,继续向下看。
  当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中。
  当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则就重复上面的过程。
  所以我们应该这样来定位PyCodeObject和pyc文件,我们说pyc文件其实是PyCodeObject的一种持久化保存方式。

 

  总结:pyc其实就是Python 预编译的的一个文件,每次运行py文件时候,会检测该pyc文件是否存在,如果不存在重新编译生成,如果存在会检查pyc和源文件哪个更新时间最新,如果源文件没有更新直接从Pyc文件执行速度快,如果源文件已经更新了呢,则会编译最新源文件生成Pyc文件。

 

三.python数据类型

 1.数值型

  整型(int):在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

  浮点型(float):浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
  浮点数的例子:3.14和52.3E-4,其中E表示10幂次方,这里表示52.3*10**-4次方的缩写。 

  
  复数(complex):例如3+4j,由实数和虚数构成,如果要遍历复数,需要分别遍历实数和虚数部分。

   2.字符串
  python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。
字符串格式化输出

  name = "alex"

  print ("i am %s " % name)  #输出: i am alex
  PS: 字符串是 %s;整数 %d;浮点数%f

  字符串常用功能:
    移除空白:strip()去首尾,lstrip()去左边,rstrip()去右边
    分割:split(',')
    长度:len()
    索引:zifucuan[i]
    切片:zifucuan[1:4]
    替换:replace('c1','c2'):把字符串里的c1替换成c2。故可以用replace(' ','')来去掉字符串里的所有 ,逗号

 3.列表
  创建列表:
  name_list = ['alex', 'seven', 'eric']或name_list = list(['alex', 'seven', 'eric'])
  
  基本操作:
    索引:从0开始,list[-1]为非空列表最后一个,list.index('a')查找a第一次出现的索引号。

    切片:list[1:5]

    追加:list.append()在末尾增加

    删除:list.pop()删除末尾/list.remove('')删除某个元素 /del list 删除列表list /list.clear()清空列表内容

    插入:insert(),list.insert(1,'a'),在1号索引位置前插入a值。

    长度:len()

    循环:for i in list:

    反转:reverse(),再次恢复需要再调用reserser()

    排序:sort(),顺序为特殊符号>数字>大写字母>小写字母(按照ASCII码的排序规则)

    扩展:extend(),list1.extend(list2),将list2扩展到list1中,list2依然存在保持不变,list1已经扩展。

    包含:(元组)


 4.元祖(不可变的列表)
    常用操作:与列表操作一样。
    ages = (11, 22, 33, 44, 55)或ages = tuple((11, 22, 33, 44, 55))
  
  5.字典
  创建字典:
    person = {"name": "mr.wu", 'age': 18}或person = dict({"name": "mr.wu", 'age': 18})
  
  常用操作:
    索引
    新增
    删除
    键、值、键值对
    循环
    长度

  6.布尔类型
  True/False
 
  7.None

  略.

   

***************数据运算符及其优先级

 

  

  

 

  

 

  

 

  

  

 

    

  

 

 

    

  

 

   **********拾遗:

  1.三元运算

     格式:retsult  =值1 if 条件 else 值2

     条件为真,输出result=值1

    条件为假,输出result=值2

      例子:

      a,b,c=1,3.5

      d=a if a>b else c

      会输出d=5

      d=a if a<b else c

      会输出d=1

  2.进制

    a.二进制 01 

    b.八进制 01234567

    c.十进制 0123456789

    d.十六进制 0123456789ABCDEF,前缀表示法BH,后缀表示法0x53

    了解一下二进制转换成16进制的方法!

  3.对象

    你找到对象了吗?

    在python里一切事物皆对象,以后别再告诉别人你没有对象啦,对象基于类创建,例如清纯类、成熟类、萌妹子类,魅惑类,知性类......

 

******************bytes数据类型:

    (1)Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用strbytes,你不能拼接字符串和字节流,也无法在字节流里搜索字符串(反之亦然),也不能将字符串传入参数为字节流的函数(反之亦然)。

    (2)bytes和str的差异:

        回到bytesstr的身上。bytes是一种比特流,它的存在形式是01010001110这种。我们无论是在写代码,还是阅读文章的过程中,肯定不会有人直接阅读这种比特流,它必须有一个编码方式,使得它变成有意义的比特流,而不是一堆晦涩难懂的01组合。因为编码方式的不同,对这个比特流的解读也会不同,对实际使用造成了很大的困扰。下面让我们看看Python是如何处理这一系列编码问题的:

        

 1 >>> s = "中文"
 2 
 3         >>> s '中文'
 4 
 5         >>> type(s) <class 'str'>
 6 
 7         >>> b = bytes(s, encoding='utf-8')
 8 
 9         >>> b b'\xe4\xb8\xad\xe6\x96\x87'
10 
11         >>> type(b) <class 'bytes'>
View Code

 

      

      

    

    (3).如上图bytes与str的相互转换:我们都知道,字符串类str里有一个encode()方法,它是从字符串向比特流的编码过程。而bytes类型恰好有个decode()方法,它是从比特流向字符串解码的过程。除此之外,我们查看Python源码会发现bytesstr拥有几乎一模一样的方法列表,最大的区别就是encodedecode

  从实质上来说,字符串在磁盘上的保存形式也是01的组合,也需要编码解码。

  如果,上面的阐述还不能让你搞清楚两者的区别,那么记住下面两几句话:

    1. 在将字符串存入磁盘和从磁盘读取字符串的过程中,Python自动地帮你完成了编码和解码的工作,你不需要关心它的过程。  

    2. 使用bytes类型,实质上是告诉Python,不需要它帮你自动地完成编码和解码的工作,而是用户自己手动进行,并指定编码格式。

    3. Python已经严格区分了bytesstr两种数据类型,你不能在需要bytes类型参数的时候使用str参数,反之亦然。这点在读写磁盘文件时容易碰到。

      在bytes和str的互相转换过程中,实际就是编码解码的过程,必须显式地指定编码格式。

      

 1 #Author Jame-Mei
 2 
 3 msg1='我爱中国'
 4 print (msg1)
 5 
 6 print ("\n将str转换成bytes编码:")
 7 print (msg1.encode(encoding='utf-8'))
 8 #python3默认为utf-8,python2.x如果没有utf-8会报错!!
 9 
10 
11 print ('\n将bytes转换成str:')
12 print(b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'.decode(encoding='utf-8'))
View Code

 

      

      (4).为何要bytes和str相互转换呢?

      涉及python网络编程,将str字符串类型转换成bytes类型进行通信和传输。

 

  

四.列表1-2的使用

   1.常见方法(增删改查)

      

 1 #Author Jame-Mei  
 2 
 3       list=[]
 4 
 5 
 6     ''' 7       list.append('a')  #在末尾添加一个元素
 8       list.insert(1,'b') #在1号位置添加b元素
 9       list.insert(2,[1,2,3]) #向list列表的2号位置中添加一个列表
10 
11     '''
12 
13     '''14       list.remove('a') #删除指定值a
15       list.pop() #删除末尾一个元素
16       del list[1] #删除list列表中1号索引的元素
17       del list  #删除List变量
18       list.clear() #清空List内的值
19      '''
20 
21     '''22       list2=['e','d','c']
23       list.extend(list2)  #扩展List,扩展后List变大,list2不变
24       list.sort()         #排序,特殊符号>>数字>>大写字母>小写字母
25       list.reverse()      #反转,需要再次调用才能恢复原样
26     '''
27 
28     '''29       列表循环 for x in list:  print(x)
30       print(list.index('e')) #查e元素第一次出现的索引位置
31       print (len(list))  #查list列表的长度
32       print (len(list2))
33       print (list[-3:]) #切片倒数三个元素
34       print (list[0])   #切片第一个元素
35       print (list[-1]) #切片最后一个元素
36       print (list[:])  #切片所有元素
37       print (list[1:6]) #顾头不顾尾(不包括6号元素)
38     '''
View Code

 

 

 

   2.其他使用方法:

    1):浅copy:

      

 1 #Author Jame-Mei
 2 
 3 names1=['jame','tom','alice']
 4 names2=names1.copy()
 5      
 6 其他浅copy的表示方法:
 7 list1=[1,2,['a',3,4]]
 8 
 9 #另外三种表示方法      
10 #p2=copy.copy(list1)
11 #p2=list1[:]
12 #p2=list(list1)
13 
14 list1[2][0]='b'
15 print (list1,p2)
16 
17 
18 #修改names1的tom
19 names1[1]='汤姆'
20 
21 #打印发现names1改变了,Names2没有改变,这是正常状态的copy.
22 print ('names1列表:',names1)
23 print ('names2列表:',names2)
24     
25 >names1列表: ['jame', '汤姆', 'alice']
26 >names2列表: ['jame', 'tom', 'alice']
27 
28 
29 
30 #向names1中添加一个列表
31 names1.insert(3,['alex','oldboy'])
32 names2=names1.copy()
33 
34 #再次修改Names1列表的值
35 names1[3][0]='ALEX'
36 
37 #打印出来发现,names1列表和names2列表都同时改变了,ALEX。这叫浅copy,只copy列表的第一层,第二层为一个内存位置。
38     
39 print ('names1列表:',names1)
40 print ('names2列表:',names2)
41     
42 >names1列表: ['jame', '汤姆', 'alice', ['ALEX', 'oldboy']]
43 >ames2列表: ['jame', '汤姆', 'alice', ['ALEX', 'oldboy']]
44 
45 如果直接用"="等于号呢:
46 #names2=names1 等于将names1的内存地址同样赋值给names2,改动其中的任何一个列表的任何一个值,两个列表同时变。
47 
48 #如果names1和names2只是为简单的数字、字符串,则不会发生这样的改变,可以动手试一试!
View Code

 

 

 

 

    浅copy的假设用途:关联账号的资金,主卡名字叫Jame,子卡名字叫Tom,里面的资金无论是主卡取钱还是存钱,或者是子卡取钱,两个都会同步。

 

      2).深copy

    

 1 import copy
 2 
 3     names2=copy().deepcopy(names1)  #深copy 
 4 
 5     names1[3][0]='ALEX'  #修改names1列表中3号列表中的0号元素值
 6 
 7     print ('names1列表:',names1)
 8     print ('names2列表:',names2)
 9     
10     names1列表: ['jame', '汤姆', 'alice', ['ALEX', 'oldboy']]
11     names2列表: ['jame', '汤姆', 'alice', ['alex', 'oldboy']]
12 
13     #发现names2没有改变,只有修改的names1发生改变了。所以names2列表深度完全的copy了names1的列表值,在内存中重新开辟了存放空间,不会因为names1列表而改变!
View Code

 

 

   3):列表循环和列表步长

   

 1 #列表循环  
 2 print ("=========循环=======================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
 3 
 4   for name in names1:
 5       print (name)
 6 
 7 
 8   #列表的按步长切片
 9   print (names1[0:-1:2])
10   #简化为
11   print (names1[::2])
12 
13   输出:
14   jame
15   汤姆
16   alice
17   ['alex', 'oldboy']
18        pycharm
19       aux
20 
21   #按照步长输出
22 
23   ['jame', 'alice', 'pycharm']
24   ['jame', 'alice', 'pycharm']    
View Code

 

       

      

 

五.元组

  元组是一种特殊的列表,一旦创建不可以修改,所以元组又叫做只读列表!

  (1.)创建

    name=('tom','男',340321198908251345)

  (2).查找,切片方法与列表一致。

  (3).count方法,index方法

   

1 #Author Jame-Mei
2 
3 name=('Jame','',340321)
4 
5 print (name.index('Jame'))  #查找第一个jame的位置
6 
7 print (name.count('')) #统计name元组中的男有几个
View Code

 

    

     (4).购物车练习:

    

       

  练习代码如下:     

#Author Jame-Mei
"""购物车练习:
需求:
1.启动程序后,让用户输入工资,然后打印商品列表
2.运行用户根据商品编号购买商品
3.用户选择商品后,检测余额是否足够,足够就直接扣款,不够提示
4.可以随时退出,退出时,打印已经购买的商品和余额
"""
goods=[['牛奶',45],['咖啡',37],['鸡蛋',58],['大米',88],['花生油',189],['面条',60],['鸡脯肉',40],['排骨',99],['牛肉',135],['烤鸭',49]]
money=0
flag=True
buygoods=[]
money =input('请输入您的工资(数字):')
if money.isdigit():
    money=int(money)
    while flag:
        print("<<<<<<============商品列表:===============>>>>>>")
        for index,good in enumerate(goods):
            #print(goods.index(good), good)
            print (index,good)
        buynum=input("---------->>请输入要购买的商品编号(q 退出):")
        if buynum=='q':
            print('您已经购买的商品:', buygoods, '余额:', money)
            exit()
        elif buynum.isdigit():
            buynum=int(buynum)
            if buynum < len(goods) and buynum >= 0:
                if goods[buynum][1] >money:
                    print ('余额',money,"不足以购买",goods[buynum][0],'请选择其他商品!')
                    continue
                else:
                    money=money-goods[int(buynum)][1]
                    buygoods.append(goods[int(buynum)])
                    print ("购买",goods[int(buynum)],"成功!")
            else:
                print ("该商品编号不存在...")
                flag=False
        else:
            print ('输入未知符号...')
            exit(1)
else:
    print ('您输入的不是数字,exit...')
    exit()

  

六.字符串常见操作

  常见方法见操作代码:

  

  1 #Author:Jame Mei
  2 name='my name is {_name} and age is {_age} old.'
  3 hello='您好,\twelcome to shanghai,welcome to welcome'
  4 varchars='meijinmeng@126.com'
  5 
  6 
  7 '''c开头的方法
  8     print(name.capitalize())    #首字母
  9     print (name.count('a'))        #统计'字符'的个数
 10     print (name.center(20,'+')) #打印50个字符,不够用'+'填补,并把name居中。
 11 
 12     输出:
 13     My name is {_name} and age is {_age} old.
 14     5
 15     ++++my name is {_name} and age is {_age} old.+++++
 16 '''
 17 
 18 '''
 19     #e开头的方法
 20     print (hello.encode())      #将str字符串转换成bytes字节码类型
 21     print (varchars.endswith('.com')) #判断varchars是否以'.com'结尾
 22     print (hello.expandtabs(tabsize=20)) #给\t键转换成20个空格
 23     
 24     输出:
 25     b'\xe6\x82\xa8\xe5\xa5\xbd,\twelcome to shanghai\xef\xbc\x8cwelcome to           welcome'
 26    True
 27    您好,                 welcome to shanghai,welcome to welcome
 28     
 29 '''    
 30     #f开头的方法
 31     print (hello.find('welcome')) #查找welcome的索引位置,其中\t也占一个位置。
 32     print (name.format(_name='alice',_age=27)) #格式化输出字符串,常用!
 33     print (name.format_map({'_name':'Tom','_age':26})) #format_map里面放的是一个字典(键值对)
 34 
 35 
 36     输出:
 37     4
 38     my name is alice and age is 27 old.
 39     my name is Tom and age is 26 old.
 40     
 41     
 42 '''
 43    #i开头
 44     print (name.index('name')) #查找'name'所在字符串索引位置,常用!!
 45     print ('123'.isdigit())    #检查是否为数字,常用!!!
 46     print ('Abc'.islower())     #判断是否为小写,常用!
 47     print ('abc'.isupper())     #判断是否为大写,常用
 48     print ('My Name Is Tom'.istitle()) #判断字符串中开头是否为大写!
 49 
 50     输出:
 51     3
 52     True
 53     False
 54     False
 55     True
 56 
 57     
 58     print ('abc123'.isalnum()) #是否是阿拉伯字符(所有英文字母和数字)
 59     print ('_1abc'.isidentifier()) #检查是否为合法的变量名,不能以数字和其他特殊符号开头则为false!
 60 
 61     输出:
 62      True
 63      True
 64 
 65       
 66     print ('ab c'.isalnum())   #有空格或者特殊符号,就为False
 67     print ('abcdef'.isalpha()) #检车是否所有都为英文字母
 68 
 69     print ('123'.isdecimal())  #检查是否为整数,带小数点为False
 70     print('123'.isnumeric())   #判断是否为纯整数,带小数点为False,和isdecimal()功能差不多。
 71 
 72     print (' '.isspace())      #判断是否是一个空格
 73     print ('abc'.isprintable())#linux终端tty文件或者driver驱动文件不可打印的,返回        False,普通文件都可以打印。
 74     
 75 
 76     输出:
 77     False
 78     True
 79     True
 80     True
 81     True
 82     True
 83 
 84  
 85 ''
 86 
 87 
 88 '''
 89     #j开头方法
 90     print ('+'.join('abc'))  #连接字符串或者列表的每个元素
 91     print ('-'.join(['a','b','c']))
 92 
 93 
 94     输出:
 95     a+b+c
 96     a-b-c
 97     
 98 '''
 99 
100 
101 
102 '''
103    #m开头的方法(不常用)
104     p=str.maketrans('jamepwd','1234567')
105     print ('jane'.translate(p))  #根据p的编码规则,来加密jane    
106 
107     输出:
108     12n4
109 '''
110 
111 
112 '''
113   #l开头的方法
114     print ('my name is tom'.ljust(50,'*')) #打印50个字符,不够字符串向左移动,*号在右边填充。
115     print ('my age is 26'.rjust(50,'+'))  #打印50给字符,不够字符串向右移动,+号左边填充。
116 
117     print ('XIAOXIE'.lower()) #把大写边小写
118     print ('daxie'.upper())  #把小写变大写
119 
120     print ('   abc'.lstrip()) #去掉左边的空格,换行,制表\t等
121     print ('ghy\n'.rstrip())  #去掉右边的空格,换行,制表\t等
122     print ('\tcedf\n'.strip()) #去首尾空格
123 
124 
125      输出:
126 
127       my name is tom************************************
128       ++++++++++++++++++++++++++++++++++++++my age is 26
129 
130      xiaoxie
131      DAXIE
132 
133      abc
134      ghy
135      cedf
136      
137  '''    
138 
139 
140 '''
141     #r开头的方法
142     print (hello.replace('welcome','hello')) #将hello变量中的全部welcome替换成hello
143     print (hello.replace('welcome','hello',1)) #将hello变量中的welcome替换1一个hello
144     print ('nihao xiaoming'.rfind('hao')) #从左往右查找元素的位置号
145     #print ('ghy\n'.rstrip())  #去掉右边的空格,换行,制表\t等
146     #print ('my age is 26'.rjust(50,'+'))
147 
148 
149      输出:
150      您好,    hello to shanghai,hello to hello
151      您好,    hello to shanghai,welcome to welcome
152      2
153 
154 '''
155 
156 
157 '''
158    #s开头的方法
159     print ('nihao,xiaoming'.split(','))  #以','逗号为分隔符将字符串,分割成一个列表。
160     print ('1+2\n3+4\n5+6'.splitlines()) #识别不同系统的换行,分割成列表。
161     print ('Alice'.swapcase())           #除首字母外,其他的都大写!
162 
163 
164     输出:
165     ['nihao', 'xiaoming']
166     ['1+2', '3+4', '5+6']
167     aLICE
168 
169 '''
170 
171 '''
172    #t开头的方法
173     print ('alice is a girl!'.title())  #每行
174 
175     输出:
176     Alice Is A Girl!
177 
178 '''
View Code

 

  

七.字典的使用 

  字典是一种key-value的数据类型,有点像我们用过的字典,通过笔画、字母来查找需要的词语或者单词。

  1.字典的语法:

   字典是另一种可变容器模型,且可存储任意类型对象。

   字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

    dic={'id':110,

      'sid':14567,

      'name':'防盗门'

      }

  2.字典的特性:

    1).字典是无序的,所以字典没有下标,不会像列表和元祖一样通过下标来查找或者删除元素。

     另外它的无序还体现在,遍历或者打印出来,它的排序可能是会变化,没有固定的顺序!!

     通过dic['key01']来进行取值。

    2):键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

      所以,不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住。

                   键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行。

   3.字典的增删改查和多层嵌套操作 

       1):增删改查操作:  

 1 #Author:Jame Mei
 2 dic1={
 3     'stu1101':'caiyuanhua',
 4     'stu01':'Alex',
 5     'stu02':'Oldboy',
 6 }
 7 
 8 
 9 '''增加,修改字典的value值:
10     dic1['stu120']='Canglaoshi'  #如果stu120键不存在,则创建并新增到字典中。
11 
12     dic1['stu02']='alex' #stu02已存在,则其值修改
13 
14     print (dic1)
15     输出:
16     {'stu1101': 'caiyuanhua', 'stu01': 'Alex', 'stu02': 'Oldboy'}
17     {'stu1101': 'caiyuanhua', 'stu01': 'Alex', 'stu02': 'alex', 'stu120': 'Canglaoshi'}
18     
19 '''#查看字典的value的值:
20 
21     print (dic1['stu120'])  #要确定字典中有'stu120及其对应的值'
22     print (dic1.get('stu121'))  #如果没有stu121,不会报错,打印返回一个None,一般安全的获取用该方法。
23  
24     输出:
25     Canglaoshi
26     None
27 
28 #查看某字符是否包含在字典中
29     print (dic1)
30     print ('stu120' in dic1)  #在py2.x中是dic1.has_key('stu120')
31 
32     输出:
33     {'stu1101': 'caiyuanhua', 'stu01': 'Alex', 'stu02': 'alex', 'stu120': 'Canglaoshi'}
34     True
35 
36 
37 '''#删除
38     del dic1['stu1101']  #删除指定的key-value !!
39     
40     dic1.pop('stu120')  #不同于列表删除末尾的,字典需要指定key来删除!
41     dic1.popitem()     #随机删除,意义不大,不能轻易使用。
42 
43     #del dic1 #删除后,再print会报错,连整个变量都删除了!
44     
45   '''
View Code

    2):多层嵌套操作:

    

  1 #Author:Jame Mei
  2 #多层嵌套操作
  3 citys={
  4     "上海":{
  5         "长宁区":['中山公园','愚园路'],
  6         "普陀区":['金山江'],
  7         "松江区":['松江大学城']
  8 
  9     },
 10     "杭州":{
 11         "西湖区":['西湖'],
 12         "上城区":['杭州火车站']
 13     },
 14     "南京":{
 15         "玄武区":['玄武湖'],
 16         "鼓楼区":['鼓楼医院']
 17     }
 18 
 19 }
 20 
 21 
 22 
 23 #Add:
 24 citys['上海']['长宁区'][0] +='免费开放,鲜花盛开绿草如茵'
 25 print (citys['上海']['长宁区'])
 26 
 27 output:
 28 ['中山公园免费开放,鲜花盛开绿草如茵', '愚园路']
 29 
 30 
 31 #update
 32 dic2={'stu01':'tomcat','stu02':'nginx'}
 33 a={1:2}
 34 dic2.update(a)
 35 print (dic2)
 36 
 37 output:
 38 {'stu01': 'tomcat', 'stu02': 'nginx', 1: 2}
 39 
 40 
 41 
 42 #items
 43 dic2={'stu01':'tomcat','stu02':'nginx'}
 44 print(dic2.items())
 45 
 46 output:
 47 dict_items([('stu01', 'tomcat'), ('stu02', 'nginx')])
 48 
 49 
 50 
 51 #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
 52 print(dict.fromkeys([1,2,3],'testd'))
 53 
 54 output:
 55 {1: 'testd', 2: 'testd', 3: 'testd'}
 56 
 57 
 58 #循环输出字典
 59 #方法1:
 60 for key in dic2:
 61     print(key,dic2[key])
 62     
 63     
 64 output:
 65 stu01 tomcat
 66 stu02 nginx
 67 
 68 
 69 #方法2:
 70 for key,value in dic2.items():
 71     print(key,value)
 72 
 73 output:
 74 stu01 tomcat
 75 stu02 nginx
 76 
 77 
 78 
 79 #key 打印字典中所有key值
 80 print (citys.keys())
 81 
 82 output:
 83 dict_keys(['上海', '杭州', '南京'])
 84 
 85 
 86 #value 打印字典所有value
 87 print (citys.values())
 88 
 89 output:
 90 dict_values([{'长宁区': ['中山公园免费开放,鲜花盛开绿草如茵', '愚园路'], '普陀区': ['金山江'], '松江区': ['松江大学城']}, {'西湖区': ['西湖'], '上城区': ['杭州火车站']}, {'玄武区': ['玄武湖'], '鼓楼区': ['鼓楼医院']}])
 91 {'上海': {'长宁区': ['中山公园免费开放,鲜花盛开绿草如茵', '愚园路'], '普陀区': ['金山江'], '松江区': ['松江大学城']}, '杭州': {'西湖区': ['西湖'], '上城区': ['杭州火车站']}, '南京': {'玄武区': ['玄武湖'], '鼓楼区': ['鼓楼医院']}, '昆山': ['华东地区工业基地', '上海11号线花桥接轨']}
 92 
 93 
 94 
 95 #setdefault默认在末尾添加一个字典及其列表
 96 citys.setdefault("昆山",{"花桥":["花桥地铁站"],"千灯镇":["千灯碧桂园"]})
 97 citys.setdefault("无锡",{"华西村":["中国第一村"],"三国影视基地":"拍戏的地方"})
 98 for x,y in citys.items():
 99     print (x,y)
100 
101 output:
102 上海 {'长宁区': ['中山公园免费开放,鲜花盛开绿草如茵', '愚园路'], '普陀区': ['金山江'], '松江区': ['松江大学城']}
103 杭州 {'西湖区': ['西湖'], '上城区': ['杭州火车站']}
104 南京 {'玄武区': ['玄武湖'], '鼓楼区': ['鼓楼医院']}
105 昆山 {'花桥': ['花桥地铁站'], '千灯镇': ['千灯碧桂园']}
106 无锡 {'华西村': ['中国第一村'], '三国影视基地': '拍戏的地方'}
View Code

 

    4.练习:三级菜单

    1):入门简陋版:

    

 1 #Author:Jame Mei
 2 #实现三级菜单的练习
 3 citys={
 4     "上海":{
 5         "长宁区":{
 6             "中山公园":{'中山公园','龙之梦购物中心'},
 7             "愚园路":{'优秀历史建筑','愚园路第一小学'}
 8         },
 9         "松江区":{
10             "松江大学城":{'大学城美女如云'},
11             "佘山":{'佘山度假区','水上公园'}
12         }
13     },
14     "杭州":{
15         "西湖区":{
16             "西湖":{'杭州西湖','雷峰塔'},
17             "太子湾":{'龙船'}
18         },
19         "上城区":{
20             "清河坊":{'中华老字号第一街'},
21             "钱学森故居":{'杭州之子'}
22         }
23 
24     },
25     "南京":{
26         "玄武区":{
27             "总统府":{'孙中山总统府'},
28             "玄武湖":{'玄武湖及公园'},
29 
30 
31         },
32         "鼓楼区":{
33             "鼓楼公园":{'鼓楼医院和鼓楼公园'},
34             "南京长江大桥":{'宏伟的南京长江大桥耸立'}
35 
36         }
37     }
38 
39 }
40 
41 
42 while True:
43     for x1 in citys:
44         print (x1)
45 
46     choice1=input("请选择进入1级菜单>>>>>>>:")
47     if choice1 in citys:
48         while True:
49             for x2 in citys[choice1]:
50                 print ('\t',x2)
51 
52             choice2=input("请选择进入2级菜单,b返回上一层>>>>>>:")
53             if choice2 in citys[choice1]:
54                 while True:
55                     for x3 in citys[choice1][choice2]:
56                         print ('\t',x3)
57 
58                     choice3=input("请选择进入3级菜单,b返回上一层>>>>>>>>:")
59                     if choice3 in citys[choice1][choice2]:
60                             for x4 in citys[choice1][choice2][choice3]:
61                                 print ('\t',x4)
62 
63                             choice4=input("最后一层,按b返回上一层!>>>:")
64                             if choice3=='b':
65                                 pass
66 
67                     if choice3=='b':
68                         break
69 
70             if choice2=='b':
71                 break
72 
73     else:
74         print ("已经是最上层,请输入菜单中的名称!")
View Code

    2):入门简陋+退出版

 1 #Author:Jame Mei
 2 #实现三级菜单的练习
 3 citys={
 4     "上海":{
 5         "长宁区":{
 6             "中山公园":{'中山公园','龙之梦购物中心'},
 7             "愚园路":{'优秀历史建筑','愚园路第一小学'}
 8         },
 9         "松江区":{
10             "松江大学城":{'大学城美女如云'},
11             "佘山":{'佘山度假区','水上公园'}
12         }
13     },
14     "杭州":{
15         "西湖区":{
16             "西湖":{'杭州西湖','雷峰塔'},
17             "太子湾":{'龙船'}
18         },
19         "上城区":{
20             "清河坊":{'中华老字号第一街'},
21             "钱学森故居":{'杭州之子'}
22         }
23 
24     },
25     "南京":{
26         "玄武区":{
27             "总统府":{'孙中山总统府'},
28             "玄武湖":{'玄武湖及公园'},
29 
30 
31         },
32         "鼓楼区":{
33             "鼓楼公园":{'鼓楼医院和鼓楼公园'},
34             "南京长江大桥":{'宏伟的南京长江大桥耸立'}
35 
36         }
37     }
38 
39 }
40 
41 
42 exit_flag=False
43 
44 while not exit_flag:
45     for x1 in citys:
46         print (x1)
47 
48     choice1=input("请选择进入1级菜单>>>>>>>:")
49     if choice1 in citys:
50         while not exit_flag:
51             for x2 in citys[choice1]:
52                 print ('\t',x2)
53 
54             choice2=input("请选择进入2级菜单,b返回上一层>>>>>>:")
55             if choice2 in citys[choice1]:
56                 while not exit_flag:
57                     for x3 in citys[choice1][choice2]:
58                         print ('\t',x3)
59 
60                     choice3=input("请选择进入3级菜单,b返回上一层>>>>>>>>:")
61                     if choice3 in citys[choice1][choice2]:
62                             for x4 in citys[choice1][choice2][choice3]:
63                                 print ('\t',x4)
64 
65                             choice4=input("最后一层,按b返回上一层!>>>:")
66                             if choice4=='b':
67                                 pass
68                             elif choice4=='q':
69                                 exit_flag=True
70 
71                     if choice3=='b':
72                         break
73                     elif choice3=='q':
74                         exit_flag =True
75             if choice2=='b':
76                 break
77             elif choice2=='q':
78                 exit_flag =True
79 
80     elif choice1=='q':
81         exit_flag=True
82 
83     else:
84         print ("已经是最上层,请输入菜单中的名称!")
View Code

    照葫芦画瓢,在每个for循环都有一个while无限循环也可以实现b上一层,q退出的效果:

    

 1 #Author:Jame Mei
 2 #自己练习三级菜单,实现随时退出,输入b返回上一层,根据输入的名称,打印它的下一级菜单。
 3 
 4 menus={
 5     "上海":{
 6         "长宁区":{
 7             "中山公园":{'中山公园','龙之梦购物中心'},
 8             "愚园路":{'优秀历史建筑','愚园路第一小学'}
 9         },
10         "松江区":{
11             "松江大学城":{'大学城美女如云'},
12             "佘山":{'佘山度假区','水上公园'}
13         }
14     },
15     "杭州":{
16         "西湖区":{
17             "西湖":{'杭州西湖','雷峰塔'},
18             "太子湾":{'龙船'}
19         },
20         "上城区":{
21             "清河坊":{'中华老字号第一街'},
22             "钱学森故居":{'杭州之子'}
23         }
24 
25     },
26     "南京":{
27         "玄武区":{
28             "总统府":{'孙中山总统府'},
29             "玄武湖":{'玄武湖及公园'},
30 
31 
32         },
33         "鼓楼区":{
34             "鼓楼公园":{'鼓楼医院和鼓楼公园'},
35             "南京长江大桥":{'宏伟的南京长江大桥耸立'}
36 
37         }
38     }
39 
40 }
41 
42 
43 not_exit=True
44 
45 while not_exit:
46     for m1 in menus:
47         print (m1)
48     choice1=input("请输入列表名称(q 退出)>>>>>>:")
49     if choice1 in menus:
50         while not_exit:
51             for m2 in menus[choice1]:
52                 print (m2)
53 
54             choice2=input("请输入列表名称(q 退出 b返回上一层))>>>>>>:")
55             if choice2 in menus[choice1]:
56                 while not_exit:
57                     for m3 in menus[choice1][choice2]:
58                         print (m3)
59 
60                     choice3=input("请输入列表名称(q 退出 b返回上一层)>>>>>>:")
61                     if choice3 in menus[choice1][choice2]:
62                         while not_exit:
63                             for m4 in menus[choice1][choice2][choice3]:
64                                 print (m4)
65 
66                             choice4=input("已经到底啦,(q 退出 b返回上一层)>>>>>>:")
67                             if choice4=='q':
68                                 not_exit=False
69                             elif choice4=='b':
70                                 break
71 
72                     elif choice3=='q':
73                         not_exit=False
74                     elif choice3 == 'b':
75                         break
76 
77             elif choice2=='q':
78                 not_exit=False
79             elif choice2 == 'b':
80                 break
81 
82     elif choice1=='q':
83                 not_exit=False
84     else:
85         print ("已经是顶层菜单了,请输入菜单中的名称(q 退出)>>>>>>:")
View Code

    3):Alex版本,没有退出功能,b 返回次数过多会报错,希望有大神解答留言!

   

 1 #Author Jame-Mei
 2 '''
 3 程序: 三级菜单
 4 要求:
 5 打印省、市、县三级菜单
 6 b 可返回上一级
 7 q 可随时退出程序'''
 8 
 9 
10 menu = {
11     '北京':{
12         '海淀':{
13             '五道口':{
14                 'soho':{},
15                 '网易':{},
16                 'google':{}
17             },
18             '中关村':{
19                 '爱奇艺':{},
20                 '汽车之家':{},
21                 'youku':{},
22             },
23             '上地':{
24                 '百度':{},
25             },
26         },
27         '昌平':{
28             '沙河':{
29                 '老男孩':{},
30                 '北航':{},
31             },
32             '天通苑':{},
33             '回龙观':{},
34         },
35         '朝阳':{},
36         '东城':{},
37     },
38     '上海':{
39         '闵行':{
40             "人民广场":{
41                 '炸鸡店':{}
42             }
43         },
44         '闸北':{
45             '火车战':{
46                 '携程':{}
47             }
48         },
49         '浦东':{},
50     },
51     '山东':{},
52 }
53 
54 
55 exit_flag = False
56 current_layer = menu
57 
58 layers = [menu]
59 
60 while not  exit_flag:
61     for k in current_layer:
62         print(k)
63     choice = input(">>:").strip()
64     if choice == "b":
65             current_layer = layers[-1]
66             print("change to laster", current_layer)
67             layers.pop()
68 
69     elif choice not  in current_layer:
70         continue
71     else:
72         layers.append(current_layer)
73         current_layer = current_layer[choice]
View Code

 

八.作业:购物车优化

  

   1.未把商品信息存入文件版,其他功能都已实现:

  

  1 #Author: http://www.cnblogs.com/Jame-mei
  2 '''
  3 week02的购物车优化:
  4 分为用户入口1 和 商家入口2:
  5     模块需求:
  6     启动后提示用户和商家,输入并判断属于用户还是商家。
  7 
  8 1.用户入口:{1.商品信息存到文件里??  2.退出的时候打印已购商品和余额}
  9     模块需求:
 10     1.启动程序后,让用户输入工资,然后打印商品列表
 11     2.运行用户根据商品名称购买商品
 12     3.用户选择商品后,检测余额是否足够,足够就直接扣款,不够提示
 13     4.可以随时退出,退出时,打印已经购买的商品和余额
 14 
 15 2.商家入口:{1.可以添加商品  2.修改商品价格}
 16     模块需求:
 17     1.进入商家入口后,有2个选项:添加商品(添加新商品:商品名称,价格),修改商品价格(修改已经存在的商品,输入对应商品名称,并修改价格)
 18     2.退出q
 19 '''
 20 
 21 
 22 #1.用户模块编写
 23 goods={'牛奶':45,'咖啡':37,'鸡蛋':58,'大米':88,'花生油':189,'面条':60,'鸡脯肉':40,'排骨':99,'牛肉':135,'烤鸭':46}
 24 money=0
 25 flag=True
 26 buygoods=[]
 27 
 28 while flag:
 29     select=input("欢迎您访问员工福利商城 1.用户 2商家(q 退出):")
 30     if select.isdigit():
 31         select=int(select)
 32         if select==1:
 33             money = input('请输入您的工资(数字):')
 34             if money.isdigit():
 35                 money = int(money)
 36                 while flag:
 37                     print("<<<<<<============商品列表:===============>>>>>>")
 38                     for index, good in enumerate(goods):
 39                         # print(goods.index(good), good)
 40                         print(index, good)
 41                     buyname = input("---------->>请输入要购买的商品名称(q 退出):")
 42                     if buyname == 'q':
 43                         print('您已经购买的商品:', buygoods, '余额:', money)
 44                         exit(0)
 45                     elif buyname in goods.keys():
 46 
 47                         if goods[buyname] > money:
 48                                 print('余额', money, "不足以购买", buyname, '请选择其他商品!')
 49                                 continue
 50                         else:
 51                             money = money - goods[buyname]
 52                             buygoods.append(buyname)
 53                             print("购买", buyname, "成功!",' 余额:',money)
 54                     else:
 55                         print("该商品不存在...")
 56                         flag = False
 57 
 58             else:
 59                 print('您输入的不是数字,exit...')
 60                 exit(0)
 61 
 62         elif select==2:
 63             # 商家模块
 64             business_flag = True
 65             while business_flag:
 66                 mod = input("1.添加商品 2.修改商品价格(q 退出)>>>>")
 67                 if mod.isdigit():
 68                     mod = int(mod)
 69                     if mod == 1:
 70                         good = input("请输入添加的商品名称:")
 71                         price = input("请输入添加商品的价格:")
 72                         if good in goods.keys():
 73                             print("商品已经存在,请勿重复添加!")
 74                         else:
 75                             goods.update({good:price})
 76                             print("添加商品成功!")
 77 
 78                     else:
 79                         good = input("请输入商品名称:")
 80                         price = input("请输入商品的价格:")
 81                         if good in goods.keys():
 82                             goods.update({good: price})
 83                         else:
 84                             print("你要修改的商品不存在!")
 85 
 86 
 87 
 88 
 89 
 90                 elif mod == 'q':
 91                     exit(0)
 92                 else:
 93                     print("请输入数字1或者2,q退出")
 94 
 95     elif select =='q':
 96         exit(0)
 97 
 98     else:
 99         print("请输入指定的编号或内容 1.用户 2.商家(q 退出):")
100         continue
101 
102 
103 
104 
105 
106 
107 #尚未做完,未把商品信息存入文件中,后期继续改造!
View Code

  

  2.添加打印用户的购买东西的清单(商品名,数量,花费金额),商品库存数量,商家的(查看商品列表,下架商品)。

  1 #Author: http://www.cnblogs.com/Jame-mei
  2 '''
  3 week02的购物车优化:
  4 分为用户入口1 和 商家入口2:
  5     模块需求:
  6     启动后提示用户和商家,输入并判断属于用户还是商家。
  7 
  8 1.用户入口:{1.商品信息存到文件里??  2.退出的时候打印已购商品和余额}
  9     模块需求:
 10     1.启动程序后,让用户输入工资,然后打印商品列表
 11     2.运行用户根据商品名称购买商品
 12     3.用户选择商品后,检测余额是否足够,足够就直接扣款,不够提示
 13     4.可以随时退出,退出时,打印已经购买的商品(名称、价格、数量)和余额(花费金额)
 14 
 15 2.商家入口:{1.可以添加商品  2.修改商品价格}
 16     模块需求:
 17     1.进入商家入口后,有2个选项:添加商品(添加新商品:商品名称,价格),修改商品价格(修改已经存在的商品,输入对应商品名称,并修改价格)
 18     2.退出q
 19         3.查看商品列表
 20          4.下架商品
 21 '''
 22 
 23 
 24 #1.用户模块编写
 25 goods={
 26     'iphone7':{'单价':4999,'库存':2},
 27     'iphone8':{'单价':5999,'库存':3},
 28     'iphonex':{'单价':7999,'库存':4},
 29     'MacbookPro':{'单价':12999,'库存':1},
 30     'Thinkpad':{'单价':7999,'库存':2},
 31     'Dell':{'单价':4999,'库存':5},
 32     '电冰箱':{'单价':2999,'库存':9},
 33     '洗衣机':{'单价':2888,'库存':2},
 34     }
 35 
 36 money=0
 37 flag=True
 38 buygoods={}
 39 
 40 
 41 while flag:
 42     select=input("欢迎您访问员工福利商城 1.用户 2商家(q 退出):")
 43     if select.isdigit():
 44         select=int(select)
 45         if select==1:
 46             money= input('请输入您的工资(数字):')
 47             if money.isdigit():
 48                 money=int(money)
 49                 sum=money
 50                 buynum = 0
 51                 while flag:
 52                     print("<<<<<<============商品列表:===============>>>>>>")
 53                     for  good,goodprice in goods.items():
 54                         print('商品名:',good,'单价:',goodprice['单价'],'库存:',goodprice['库存'])
 55                     buyname = input("---------->>请输入要购买的商品名称(q 退出):").strip()
 56 
 57                     if buyname == 'q':
 58                         print('>>>>>>请查看您的购物清单>>>>>>>:')
 59                         for key,value in buygoods.items():
 60                             print ('购买商品:',key,value)
 61                         print ('您共消费:',(sum-money),'','余额为:',money)
 62                         print ('谢谢您的光临,请下次再来!')
 63 
 64                         exit(0)
 65                     elif buyname in goods.keys():
 66 
 67                         if goods[buyname]['单价'] > money:
 68                                 print('您的余额为:', money, "不足以购买", buyname, '请选购其他商品!')
 69                                 continue
 70                         else:
 71                             if goods[buyname]['库存']>0:
 72                                 buynum+=1
 73                                 money= money - goods[buyname]['单价']
 74 
 75                                 buygoods.update({buyname:{'单价':goods[buyname]['单价'],'数量':buynum}})
 76                                 goods[buyname]['库存'] = goods[buyname]['库存'] - 1
 77                                 print("购买", buyname, "成功!",' 余额:',money)
 78 
 79                             else:
 80                                 print ('该商品已经被抢购一空,请购买其他商品吧....')
 81                                 continue
 82                     else:
 83                         print("您输入的该商品名称不存在,请确认后重新输入...")
 84                         continue
 85 
 86             else:
 87                 print('您输入的不是数字,exit...')
 88                 exit(0)
 89 
 90         elif select==2:
 91             # 商家模块
 92             business_flag = True
 93             while business_flag:
 94                 mod = input("1.添加商品 2.修改商品价格 3.查看现有商品列表 4.下架商品 (q 退出)>>>>")
 95                 if mod.isdigit():
 96                     mod = int(mod)
 97                     if mod == 1:
 98                         good = input("请输入添加的商品名称:").strip()
 99                         if good in goods.keys():
100                             print("商品已经存在,请勿重复添加!")
101                         else:
102                             price = input("请输入添加商品的价格:")
103                             goodnum = input("请输入添加商品的库存:")
104                             goods.update({good:{'单价':price,'库存':goodnum}})
105                             print("添加商品成功!")
106 
107                     elif mod==2:
108                         good = input("请输入商品名称:").strip()
109                         price = input("请输入商品的价格:")
110                         if good in goods.keys():
111                             goods.update({goods,{'单价':price}})
112                         else:
113                             print("你要修改的商品不存在,请确认后重新输入!")
114 
115 
116                     elif mod==3:
117                         print("<<<<<<============商品列表:===============>>>>>>")
118                         for good, goodprice in goods.items():
119                             # print(goods.index(good), good)
120                             print('商品名:', good, '单价:', goodprice['单价'], '库存:', goodprice['库存'])
121 
122                     elif mod==4:
123                         good = input("请输入商品名称:").strip()
124                         del goods[good]
125 
126                 elif mod == 'q':
127                     exit(0)
128                 else:
129                     print("请输入数字1,2,3,4, q退出")
130 
131     elif select =='q':
132         exit(0)
133 
134     else:
135         print("请输入指定的编号或内容 1.用户 2.商家(q 退出):")
136         continue
137 
138 
139 
140 
141 
142 
143 #尚未做完,未把商品信息存入文件中,后期继续改造!    
View Code

 

 

  3.添加功能把商品信息存入文件(操作file,def 函数分模块版本,ps抄的)

  1 #Author:http://www.cnblogs.com/Jame-mei
  2 '''week02的购物车优化:
  3    分为用户入口1 和 商家入口2:
  4        模块需求:
  5        启动后提示用户和商家,输入并判断属于用户还是商家。
  6 
  7    1.用户入口:{1.商品信息存到文件里??  2.退出的时候打印已购商品和余额}
  8        模块需求:
  9       1.启动程序后,让用户输入工资,然后打印商品列表
 10       2.运行用户根据商品名称购买商品
 11       3.用户选择商品后,检测余额是否足够,足够就直接扣款,不够提示
 12       4.可以随时退出,退出时,打印已经购买的商品和余额
 13 
 14   2.商家入口:{1.可以添加商品  2.修改商品价格}
 15       模块需求:
 16       1.进入商家入口后,有2个选项:添加商品(添加新商品:商品名称,价格),修改商品价格(修改已经存在的商品,输入对应商品名称,并修改价格)
 17      2.退出q
 18  '''
 19 
 20 product_list = [
 21     ('Iphone',5288),
 22     ('Mac pro',12000),
 23     ('Bike',800),
 24     ('Watch',36000),
 25     ('Coffe',39),
 26     ('Python book',120),
 27 ]
 28 
 29 #将商品信息打印到console窗口下
 30 def print_write_product():
 31     print_list()
 32     # 将商品信息写入product.txt文件
 33     f = open("product.txt", 'w')
 34     f.write(str(product_list) + "\n")
 35     f.close()
 36 
 37 
 38 #用户输入自己的薪水
 39 def choose_product():
 40     salary = input("Please input your salary :")
 41     if salary.isdigit():
 42         salary = int(salary)
 43     #用户选择要购买的商品
 44     shopping_list = []
 45     while True:
 46         user_choice = input('Please input your wanna product number(q 退出):')
 47         if user_choice.isdigit():
 48             user_choice = int(user_choice)
 49             if user_choice >=0 and user_choice <= len(product_list):
 50                 p_item = product_list[user_choice]
 51                 if salary >=  p_item[1]:
 52                     shopping_list.append(p_item)
 53                     salary -= p_item[1]
 54                     print("Added %s into shopping cart,your current balance is %s " % (p_item, salary))
 55                 else:
 56                     print('Your salary is not enough !Your balabce only [%s] !'%salary)
 57             else:
 58                 print("Product code [%s] is not exist !" % user_choice)
 59         elif user_choice =='q':
 60             f = open("shopping_record.txt", 'w')
 61             print('--------------shopping_list---------------')
 62             for p in shopping_list:  # python 中直接使用的变量初始化的 就是0,不用定义再使用
 63                 print(p)
 64                 f.write(str(p) + "\n")
 65             f.write(str(salary) + "\n")
 66             print('Your balance :', salary)
 67             f.close()
 68             print('exit....')
 69             exit()
 70         else:
 71             print('Invalide choice ')
 72 
 73 
 74 
 75 #专门给商家提供的入口:
 76 #增加货物
 77 def add_product(tuple):
 78     product_list.append(tuple)
 79     print_list()
 80 
 81 #修改价格
 82 def modify_price(i):
 83     print('Input the changed product and price:')
 84     product_list[i] = input(tuple)
 85     print_list()
 86 
 87 #请用户输入自己是商家还是用户
 88 def identity():
 89     i = input('business商家 输入:b | client用户 输入:c | other其他 退出 : ''\n')
 90     return i
 91 
 92 #商家可执行菜单选项
 93 def select_service():
 94     i = input('adding goods--------------------------> a:''\n'
 95               'change the price of the product-------> c:''\n')
 96     return i
 97 
 98 def print_list():
 99     for index, item in enumerate(product_list):  #enumerate 能把下标取出来
100         print(index, item)
101 
102 
103 # 主函数
104 
105 i = identity()
106 if i == 'b':
107     j = select_service()
108     if j == 'a':
109         print_list()
110         a = input('Input adding product and price:')
111         add_product(a)
112         f = open("c_product.txt", 'w')
113         f.write(str(product_list) + "\n")
114         f.close()
115     elif j == 'c':
116         print_list()
117         c = int(input('Input what you wanna changed number:'))
118         modify_price(c)
119         f = open("c_product.txt", 'w')
120         f.write(str(product_list) + "\n")
121         f.close()
122 elif i == 'c':
123     print_write_product()
124     choose_product()
125 else:
126     print('Invalied input !')
View Code

 

  

 

 

posted @ 2018-03-11 15:30  meijinmeng  阅读(545)  评论(0编辑  收藏  举报