目录

一、基础概念

  1、模块

    1)os模块

    2)sys模块

  2、pyc文件

  3、数据类型

    1)数字

    2)布尔值

    3)字符串

  4、数据运算

  5、运算符

  6、赋值运算

  7、逻辑运算

  8、成员运算

  9、身份运算

  10、二进制运算

  11、列表与元组

    1)列表切片

    2)增加列表内容

    3)列表删除

    4)列表修改

    5)列表查询

    6)列表统计

    7)列表反转与排序

    8)清空列表

    9)列表的合并

    10)拷贝

    11)元组

  12、字符串操作

  13、字典

    1)创建

    2)修改

    3)添加

    4)删除

    5)查找

    6)key value打印

    7)setdefault函数

    8)update函数

    9)fromkeys函数

    10)字典打印

二、作业

购物车程序

 

一、基础概念

1、模块

python中有两种类型的模块,一种是标准模块,即python自带模块,另外一种是第三方模块,这种模块需要通过easy_install或者pip方式下载

第一周学习的getpass模块即标准模块,通过import getpass即可调用

系统管理中常用的两个模块,os与sys模块

  1)os模块

    os.system:

      

>>> import os
>>> os.system('df -h')
Filesystem                                                                                                      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1                                                                                                     233Gi  201Gi   31Gi    87% 1734983 4293232296    0%   /
devfs                                                                                                          328Ki  328Ki    0Bi   100%    1136          0  100%   /dev
map -hosts                                                                                                       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home                                                                                                    0Bi    0Bi    0Bi   100%       0          0  100%   /home

0

    os.system命令为一次性命令,命令输出在屏幕上,没有保存值,对此做实验对比:

>>> cmd = os.system('df -h')
Filesystem                                                                                                      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1                                                                                                     233Gi  201Gi   31Gi    87% 1734983 4293232296    0%   /
devfs                                                                                                          328Ki  328Ki    0Bi   100%    1136          0  100%   /dev
map -hosts                                                                                                       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home                                                                                                    0Bi    0Bi    0Bi   100%       0          0  100%   /home
/dev/disk2s1                                                                                                   121Gi   74Gi   46Gi    62%  609531     380413   62%   /Volumes/TK卡>>> print(cmd)
0

    打印cmd只会返回0,因为该命令输出正确,返回0

    os.popen():

    如果需要将命令输出返回值保存在内存中,需要使用os.popen函数,通过read()方式来获取该命令返回值:

    

>>> cmd = os.popen('df -h')
>>> print(cmd)
<open file 'df -h', mode 'r' at 0x10c9385d0>

            

>>> cmd = os.popen('df -h')
>>> print(cmd)
<open file 'df -h', mode 'r' at 0x10c9385d0>
>>> cmd = os.popen('df -h').read()
>>> print(cmd)                    
Filesystem                                                                                                      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1                                                                                                     233Gi  201Gi   31Gi    87% 1734987 4293232292    0%   /
devfs                                                                                                          328Ki  328Ki    0Bi   100%    1136          0  100%   /dev
map -hosts                                                                                                       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home                                                                                                    0Bi    0Bi    0Bi   100%       0          0  100%   /home

   os.mkdir():

     os.mkdir函数可以创建目录

>>> os.mkdir('test')
>>> os.system('ls -l')
Applications            Downloads               Music                   PycharmProjects         bcache                  test

  2) sys模块

  sys为系统自带模块,属于系统级别所以不会像os模块那样在放在/Library/Python/2.7/site-packages/

    sys.path函数:

    sys.path函数可以打印python使用的所有环境变量

sys.path
['', '/Library/Python/2.7/site-packages/Django-1.8.3-py2.7.egg', '/Library/Python/2.7/site-packages/pip-7.1.2-py2.7.egg',]

     sys.argv函数:

    sys.argv可以打印出所携带的变量

vim test.py
import sys
print(sys.argv)
print(sys.argv[3]) #运行结果: mymacbook-pro:test Gavin$ python test.py 4 5 6 ['test.py', '4', '5', '6'] 6


 

import sys
#print(sys.argv)
a = int(sys.argv[1]) #sys.argv调用参数需要加'[]'

b = int(sys.argv[2])
c = a + b
print(c)

 

 

 

2、pyc文件

python属于解释型语言,但是并非不进行编译,python在首次运行时会先编译该句再运行该句,而java会在运行前将所有语句都进行编译,然后在运行,这个和python的运行机制略有不同,python在运行完毕后会生成对应该程序的pyc文件,在第二次运行时如果发现有pyc文件会直接将该pyc文件导入内存中运行,加快运行速度,在python3中,在每次运行程序后,如果下一次运行发现该原始文件的修改日期比对应pyc文件修改日期更近,会直接运行该原始文件,python3使用这种方式来避免重新修改后而没有生效的问题

 

3、数据类型

  1)数字

    int(整形),在python3中去掉了python2中long(长整形)

    float(浮点数)

  2)布尔值:

    真或假  表示 1或者0   在python中也可以使用True和False表示

  3)字符串

    a = ‘abcded’

4、数据运算

  +  -   *  /  %  其中%或者/被用来做奇数偶数校验

5、运算符

  == 等于

  != 不等于

  <>不等于 很少使用

  >=大于等于

  <=小于等于

6、赋值运算

  =

  +=  

  -=

  *=

  /=

  **=

  //=

7、逻辑运算

  and

  or

  not

8、成员运算

  in

  not in 

9、身份运算

  is

  is not

10、二进制运算

  &

  |

  ^

  ~

  <<

  >>  

11、列表与元组

  列表与元组都是集中记录数据的数据结构,不同的是,列表可以修改,但是元组没法修改

  列表操作方法:

  1)列表切片

>>> name = ['tony', 'rose', 'gavain','peter', 'tom']   #创建一个list,列表包括index与存储的数值,index是不显示的
>>> print(name[1])  #list的index是从0开始的,所以第一位是rose
rose
>>> print(name[1:4])#可以对list进行切片操作,list切片操作从确定的位开始以到最后一位减一位结束,即index 1  开始到4-1即index3结束,这里显示为rose开始,peter结束
['rose', 'gavain', 'peter']
>>> print(name[:])#如果输入:表示显示全部内容,这种方式也可以作为列表浅拷贝的一种方式
['tony', 'rose', 'gavain', 'peter', 'tom']
>>> print(name[2:-1])  #-1表示最后一位
['gavain', 'peter']
>>> print(name[-1])
tom
>>> print(name[-3:-1])   #list的index只能从左向右书写,即使为负数也需要按照该方式书写
['gavain', 'peter']
>>> print(name[1:])
['rose', 'gavain', 'peter', 'tom']  #如果只写了开始位置没有写切片的结束位置就表示到最后
>>> print(name[0:])#index位置为0可以忽略,即和name[:]输入一致
['tony', 'rose', 'gavain', 'peter', 'tom']
>>> print(name[0:-1])
['tony', 'rose', 'gavain', 'peter']
>>> print(name[0:])
['tony', 'rose', 'gavain', 'peter', 'tom']
>>> print(name[-2])
peter

 

   2)增加列表的内容

>>> name.append('alex')  #默认情况下,使用append方式进行增加,appen方式只能将增加的内容插入在列表的最后
>>> print(name)
['tony', 'rose', 'gavain', 'peter', 'tom', 'alex']
>>> name.insert(1,'john')  #如果需要指定位置插入列表内容,需要使用insert,insert方法可以指定需要插入到某个位置,然后在该位置插入内容,原来index位置的内容会自动后移
>>> print(name)
['tony', 'john', 'rose', 'gavain', 'peter', 'tom', 'alex']

  3)列表的删除

>>> name.pop()  #如果pop方法不加参数,会默认删除最后一个list选项
'alex'
>>> name.pop(2)  #如果需要删除某一特定内容,需要指定该内容所在index位置
'rose'
>>> name.remove('gavain')  #与pop不同,remove方法是直接输入需要删除的内容
>>> print(name)
['tony', 'john', 'peter', 'tom']
>>> del name[3]   # 通过del加list的index可以直接删除该列表对应的内容
>>> name
['tony', 'john', 'peter']
>>> del name  #如果del后面直接跟列表名称而没有加index,就表示删除整个列表
>>> name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

  4)列表的修改

>>> name = ['tony', 'rose', 'gavain','peter', 'tom']
>>> name[1] = 'john'  #需要修改的内容可以直接在其对应的index位置进行修改
>>> name
['tony', 'john', 'gavain', 'peter', 'tom']

  5)列表的查询

>>> name
['tony', 'john', 'gavain', 'peter', 'tom']
>>> 
>>> name.index('peter')    #通过index方法可以列出需要查找内容对应的index位置
3
>>> 
>>> 
>>> name.index('tom')
4
>>> name.index('a')  #如果查询的内容不存在,index方法会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list

  6)列表的统计

>>> name = ['tony', 'rose','tom' ,'gavain','peter', 'tom']
>>> name.count('tom')   #count表括号里的内容再列表里出现的次数
2
>>> name.count('tony')
1
>>> name.count('a')
0

  7)列表的反转与排序

>>> name = ['tony', 'rose','tom' ,'gavain','peter', 'tom']
>>> name.reverse()   #通常reverse只是单纯的将原列表进行反转,不考虑顺序
>>> name
['tom', 'peter', 'gavain', 'tom', 'rose', 'tony']
>>> name.sort()  #对列表进行排序
>>> name
['gavain', 'peter', 'rose', 'tom', 'tom', 'tony']
>>> name.sort(reverse=True) #可以通过在sort内的reverse=True方式将列表反向排序
>>> name
['tony', 'tom', 'tom', 'rose', 'peter', 'gavain']

  8)清空列表

>>> name
['tony', 'tom', 'tom', 'rose', 'peter', 'gavain']
>>> name.clear()  #clear方法清空列表
>>> name
[]

  9)列表的合并

>>> name = ['tony', 'rose','tom' ,'gavain','peter', 'tom']
>>> name2 = [1,2,3]
>>> name2
[1, 2, 3]
>>> name.extend(name2) #extend方式通过将name2合并到name中
>>> name
['tony', 'rose', 'tom', 'gavain', 'peter', 'tom', 1, 2, 3]

  10)拷贝

  copy分为浅拷贝与深度拷贝,其中浅拷贝只会拷贝原有列表的内存地址,所以对原有列表改变会影响新列表,而深拷贝直接开辟新的内存空间,修改原有列表不会影响源列表内容 

>>> import copy      
>>> name3 = copy.copy(name)  #也可以写作name3 = name[:]  或name3 = name.copy()
>>> name3      
['tony', 'rose', 'tom', [1, 2, 3], 'gavain', 'peter', 'tom']
>>> name[3][0] = 'a'
>>> name
['tony', 'rose', 'tom', ['a', 2, 3], 'gavain', 'peter', 'tom']
>>> name3
['tony', 'rose', 'tom', ['a', 2, 3], 'gavain', 'peter', 'tom']
>>> name = ['tony', 'rose','tom' ,[1, 2, 3],'gavain','peter', 'tom']
>>> name3 = copy.deepcopy(name)  #通过copy模块的deepcopy方式进行深度拷贝
>>> name[3][0] = 'a'
>>> name
['tony', 'rose', 'tom', ['a', 2, 3], 'gavain', 'peter', 'tom']
>>> name3
['tony', 'rose', 'tom', [1, 2, 3], 'gavain', 'peter', 'tom']

  11)元组

  元组被称为不能修改的列表,也就意味着元组一旦写完就没法进行修改,在列表显示的方法中,只有count与index可以被元组所用

>>> name = ('tony', 'rose','tom' ,[1, 2, 3],'gavain','peter', 'tom')   
>>> name
('tony', 'rose', 'tom', [1, 2, 3], 'gavain', 'peter', 'tom')
>>> name[3][0] = 'a'  #虽然元组没法修改,但是元组内嵌套的列表是可以修改的
>>> name
('tony', 'rose', 'tom', ['a', 2, 3], 'gavain', 'peter', 'tom')
>>> name.count('rose')
1
>>> name.count('a')
0
>>> name.index('gavain')
4

 

12、字符串操作

>>> name = 'my name is gavin!'
>>> 
>>> 
>>> 
>>> name.capitalize()   #首字母大写
'My name is gavin!'
>>> name.count('a')   #查看字母在该字符串中存在多少
2
>>> name.count('m')   #查看字母m在该字符中存在次数
2
>>> name.count('g')
1
>>> name.center(50,'+')   #在占50个字符的位置,如果原有字符不够会用+顶替
'++++++++++++++++my name is gavin!+++++++++++++++++'
>>> name.endswith('in')   #判断最后字符是否为in
False
>>> name.endswith('!')
True
>>> name = 'my name\t is gavin!'
>>> name.expandtabs(tabsize=30)  #如果字符串中存在tab,会修改tab占用字符的多少
'my name                        is gavin!'
>>> name.find('gavin')  #在name中查找是否有gavin,如果有就返回所在位置
12
>>> name = 'my name is {name} ,I am {year} old'
>>> name.format(name='gavin', year='23')   #通过赋值方式对字符串进行动态修改
'my name is gavin ,I am 23 old'
>>> name.format_map({'name': 'gavin', 'year': 23})#通过字典赋值方式对字符串进行赋值
'my name is gavin ,I am 23 old'
>>> name = 'abcd'   
>>> name.isalnum()   #判断是否全部为字符或者数字
True
>>> name.isalpha()  #判断是否全部为字符
True
>>> name = 'my name is gavin'  
>>> name.isalnum()  #增加了空格后,判断是否全为字符或数字会显示false
False
>>> name.isalpha()  #增加了空格后,判断是否全为字符显示false
False
>>> name = 'abcd1234'
>>> name.isalnum()
True
>>> name.isalpha()
False
>>> name = '103030' 
>>> name.isdecimal()  
True
>>> name = '103030.0'
>>> name.isdecimal()   #判断是否为十进制数字,但是如果其他任意字符都会显示false
False
>>> name = '103030'
>>> name.isdigit()   #判断是否为数字  isdigit
>>> 'a1j'.isidentifier()  #判断是否为合法的变量名
True
>>> name = '103030'
>>> name.isnumeric()#判断name变量是否为数字
True
>>> name = '103030a'
>>> name.isnumeric()
False
>>> name = ' '
>>> name.isspace()  #判断是否为空格
True
>>> name.istitle() #判断是否每个字母首字符都大写
False
>>> name.isprintable()  #判断是否为可打印的,在linux中如果发现tty设备会显示false
True
>>> name.isupper()#判断是否都为大写
False
>>> name.ljust(50,'+') #右面加50个+
'my name is gavin++++++++++++++++++++++++++++++++++'
>>> name.rjust(50,'+')  #左边加50个+
'++++++++++++++++++++++++++++++++++my name is gavin'
>>> name.lower() #变为小写
'my name is gavin'
>>> name.upper()
'MY NAME IS GAVIN'
>>> name = '\nmy name is gavin\n'
>>> name
'\nmy name is gavin\n'
>>> print(name)

my name is gavin

>>> name.rstrip()
'\nmy name is gavin'
>>> name.lstrip()
'my name is gavin\n'
>>> name.strip()  #strip会去掉空格与回车符
'my name is gavin'
>>> d = str.maketrans('abcdef','123456')
>>> name.translate(d) #将name中abcdef对应替换为123456
'\nmy n1m5 is g1vin\n' 
>>> name.replace('a','A') #将name中全部a替换为A
'my nAme is gAvin'
>>> name.replace('a','A',1)  #将a替换为A,后面的1表示只替换第一次出现的a
'my nAme is gavin'
>>> name.rfind('a')#从左面开始找最右面的a
12
>>> name.split()  #默认情况下将空格为分隔符,将字符串放入列表中
['my', 'name', 'is', 'gavin']
>>> name.splitlines()  #按照换行来分
['my name is gavin']
>>> name.title() #每个首字符都大写
'My Name Is Gavin'
>>> name.zfill(50)  #如果不够50就用0填充,对16进制有效
'0000000000000000000000000000000000my name is gavin'

 

 13、字典

   1)创建

  

>>> name = {'stu001': 'jinxing', 'stu002': 'lichen', 'stu003' : 'luhan', 'stu004': 'dengchao'}
>>> name
{'stu004': 'dengchao', 'stu002': 'lichen', 'stu001': 'jinxing', 'stu003': 'luhan'}

  2)修改

>>> name['stu001'] = 'zhengkai'
>>> name
{'stu004': 'dengchao', 'stu002': 'lichen', 'stu001': 'zhengkai', 'stu003': 'luhan'}

  3)添加

>>> name['stu005'] = 'wangzulan'
>>> name
{'stu005': 'wangzulan', 'stu004': 'dengchao', 'stu002': 'lichen', 'stu001': 'zhengkai', 'stu003': 'luhan'}

对于修改与添加的说明:当name中的key值存在的情况下,做该key值的添加操作被视为修改,如果key值不存在就变成了真正他添加

 

  4)删除

>>> name.pop('stu003')  #与列表不同,字典的pop方法内必须加key值不然会报错
'luhan'
>>> name
{'stu005': 'wangzulan', 'stu004': 'dengchao', 'stu002': 'lichen', 'stu001': 'zhengkai'}
>>> name.popitem()  #popitem方法会随机删除一个key与对应的value值
('stu005', 'wangzulan')
>>> name
{'stu004': 'dengchao', 'stu002': 'lichen', 'stu001': 'zhengkai'}
>>> del name['stu002']   #del是一个通用方法,如果跟了字典的key值就会删除该key与对应的value
>>> name
{'stu004': 'dengchao', 'stu001': 'zhengkai'}
>>> del name  #如果只是del 该字典而没有加key,会删除整个字典
>>> name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

  5)查找

>>> name['stu001']  #通过字典的key可以找到对应的value
'jinxing'
>>> name['stu002']
'lichen'
>>> name['stu005']  #以这种方式进行字典value查找的话会有一个缺点即如果没有这个key,会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'stu005'
>>> name.get('stu001')   
'jinxing'
>>> name.get('stu005')#get是一种相对安全的方式,如果没有该key不会报错,只会不显示

  6)key  value打印

>>> name.keys()  #得到字典的key值
dict_keys(['stu004', 'stu002', 'stu001', 'stu003'])
>>> name.values()#得到字典的value值
dict_values(['dengchao', 'lichen', 'jinxing', 'luhan'])

  7)setdefault函数

>>> name.setdefault('stu001', 'kkk') #如果key存在只会打印,不会对字典进行修改
'jinxing'
>>> name
{'stu004': 'dengchao', 'stu002': 'lichen', 'stu001': 'jinxing', 'stu003': 'luhan'}
>>> name.setdefault('stu006', 'kkk')   #如果key不存在会添加到字典中
'kkk'
>>> name
{'stu004': 'dengchao', 'stu006': 'kkk', 'stu002': 'lichen', 'stu001': 'jinxing', 'stu003': 'luhan'}

  8)update函数

>>> name
{'stu004': 'dengchao', 'stu006': 'kkk', 'stu002': 'lichen', 'stu001': 'jinxing', 'stu003': 'luhan'}
>>> name2 = {'stu001': 'baby', 'stu007': 'wangbaoqiang'}
>>> name.update(name2)  #字典合并,如果key重合会修改原字典name中的value,如果不存在会添加到原字典name中
>>> name
{'stu001': 'baby', 'stu003': 'luhan', 'stu007': 'wangbaoqiang', 'stu006': 'kkk', 'stu002': 'lichen', 'stu004': 'dengchao'}
>>> 

  9)fromkeys函数

>>> name3 = dict.fromkeys(['stu100', 'stu101', 'stu102'])  #构造字典
>>> name3
{'stu101': None, 'stu100': None, 'stu102': None}
>>> name3 = dict.fromkeys(['stu100', 'stu101', 'stu102'], 'default')#如果后面出现任何数值,value均为该值
>>> name3
{'stu101': 'default', 'stu100': 'default', 'stu102': 'default'}

  10)字典的打印

>>> for i in name:print(i,name[i])
... 
stu001 baby
stu003 luhan
stu007 wangbaoqiang
stu006 kkk
stu002 lichen
stu004 dengchao
>>> for k,v in name.items():print(k,v)
... 
stu001 baby
stu003 luhan
stu007 wangbaoqiang
stu006 kkk
stu002 lichen
stu004 dengchao
#上述两种方法均表示字典的key与value打印,但是第一种方法是得到key后根据key打印value,而后一种方法需要在得到key与value后将两者变为元组后打印,效率低,建议采用第一种方式打印字典

 

 二、作业

购物车程序

该程序有两种登录模式:

1、买家登录,买家登录后首先会判断是否是第一次登录,即账号是否存有工资,如果没有需要重新输入,如果有就用上次剩余的工资购物,买家在购物完毕后,会保存购物清单与剩余工资

2、卖家登录,卖家登录后可以添加或者删除商品,添加商品时,如果遇到同样的商品,可以修改商品的价格,删除商品时,根据商品的序号进行删除,当修改完毕后会保存到商品文件中

3、在任意一层登录,均可以使用d跳转到上级目录,可以使用q来退出整个程序

msg = '''
    please input your chioce:
        1:  用户登录入口
        2:  卖家登录入口
        q:  退出
      '''
add_msg = '''
    please input your choice:
        Add:  add the list of production
        Sub:  remove the list of production
          d:  break to the top menu!
    '''
product_list = []
shopping_list = []


try:
    with open('shopping-list.txt' ,'r') as f:    #判断买家购物清单是否存在
        for items in f.readlines():
            shops = items.strip()
            shopping_list.append(shops)  #如果存在将原有已购物清单文件存入列表中

except IOError:
        print('shopping-list.txt is empty!')




try:
    with open('product.txt', 'r') as f:     #判断卖家清单是否存在
        for shop_items in f.readlines():
            product = shop_items.split(' ')[0].strip()  #取出文件的第一项
            momey = int(shop_items.split(' ')[1].strip())  #取出文件的第二项 ,价格项,并将该项变为int格式
            shop_item = (product, momey)  #将两项变为元组形式
            product_list.append(shop_item)
except IOError:
    print('production.txt is empty!')

try:
    with open('salary.txt','r') as f:  #判断工资列表是否已存在
        salary = f.read()
    salary = int(salary)   #默认文件中存字符型数字,需要转换成int类型
except IOError:
    salary =0      #如果该文件不存在,默认将salary变为0
    print('the salary.txt is not exist!')


while True:
    print(msg)
    choice_key = input('your choice: ')   #根据msg提示输入用户选择
    if choice_key == '1':
        if salary == 0:  #当salary.txt不存在时,需要用户自己输入工资
            salary = input('please input your salary: ')
            if salary.isdigit():  #判断工资类型是否为数字,如果为数字类型转换为int
                salary = int(salary)
            elif salary == 'q' or salary == 'quit':  #在该位置输入q或者quit均推出程序
                exit('you do not want buy anything!')
            else:
                print('please input your salary!')
        else:
            salary = int(salary)  #如果工资文件存在,将文件中的工资文件取出,转为int类型进行后续操作
            print('your balance is \033[32;1m%s\033[0m' %salary)   #打印存在的工资,已方便购物
        while True:
            for k,v in enumerate(product_list):  #打印卖家的清单,方便买家购物
                print(k, end='')
                print('.',end=' ')
                for i in v:
                    print(i,end=' ')
                print('\n')
            #print(k,v)
            your_choice = input('please input your choice: ')    
            if your_choice.isdigit():   #判断买家输入的数字是否为数字
                your_choice = int(your_choice)
                if your_choice < len(product_list) and your_choice >= 0:   #要求买家在购物过程中要按照指定的范围选择,如果超过商品列表的长度,需要提示买家,如果正确,按照下列操作
                    if salary >= product_list[your_choice][1]:  #查看工资是否高于商品的价格
                        salary -= product_list[your_choice][1]  #当高于商品价格,购买该商品,扣除工资
                        buy_thing = product_list[your_choice][0]
                        shopping_list.append(buy_thing)        #将该商品放入购物列表中
                        print('you have add %s in your shopping list,your balance is \033[31;1m%s\033[0m' %(buy_thing, salary))  #打印已买到的商品以及所剩的余额
                    else:
                        print('\033[41;1myour balance is only %s ,you cant not afford it\033[0m' %salary)   #如果余额不足以购买该商品,需要提示用户
                else:
                    print('product code \033[32;1m[%s]\033[0m is not exist!' %your_choice)


            elif your_choice == 'q' or your_choice == 'quit':     #当用户输入q或者quit时需要如下操作
                if len(shopping_list) != 0:                       #判断购物车大小,如果购物车中有商品打印购物车的商品列表
                    print('your choice list'.center(50,'-'))
                    for i in shopping_list:
                        print(i,end = ' ')
                        with open('shopping-list.txt','w') as file:   #将购物车的列表写入购物车文件中保存
                                file.write(i)
                                file.write('\n')
                    print('\n')
                    with open('salary.txt','w') as f:      #需要将购物后剩余余额存入salary文件
                        salary = str(salary)
                        f.write(salary)
                    exit('end of shopping'.center(50,'-'))   
                else:
                    with open('salary.txt','w') as f:    
                        salary = str(salary)
                        f.write(salary)
                    exit('the shopping_list is empty')


            elif your_choice == 'd':                     #选择d时,需要调整到上级目录
                if len(shopping_list) != 0:              #同样也需要查看此时购物车是否存有购物的商品
                    print('your choice list'.center(50,'-'))
                    for i in shopping_list:
                        print(i,end = ' ')
                        with open('shopping-list.txt','w') as file:    #将购物车的列表存入文件中
                                file.write(i)
                                file.write('\n')
                    print('\n')
                    print('end of shopping'.center(50,'-'))
                    with open('salary.txt','w') as f:
                        salary = str(salary)
                        f.write(salary)
                    break
                else:
                    with open('salary.txt','w') as f:         
                        salary = str(salary)
                        f.write(salary)
                    print('the shopping_list is empty')
                    break
            else:
                print('wrong input...please choice the right number')



    elif choice_key == '2':
        while True:
            print(add_msg)
            add_choice = input('please input your add_choice: ')       #根据提示选择增加或删除商品
            if add_choice == 'Add':
                while True:
                    for k,v in enumerate(product_list):
                        print(k,end='')
                        print('.',end=' ')
                        for i in v:
                            print(i,end=' ')
                        print('\n')

                    shop_add = input('please input production of your add:')
                    if shop_add == 'q':
                        for a in product_list:
                            with open('product.txt','w') as files:
                                files.write(a[0])
                                files.write(' ')
                                files.write(str(a[1]))
                                files.write('\n')
                        exit('end of adding the production-list')
                    elif shop_add == 'd':
                        for a in product_list:
                            with open('product.txt','w') as files:   #在商品存入时需要注意,a为列表中元组,需要在a中再取数值来存入文件
                                files.write(a[0])
                                files.write(' ')
                                files.write(str(a[1]))
                                files.write('\n')
                        break
                    else:
                        for shop_index, shop_value in enumerate(product_list):    #当没有输入q或者d时,表示需要添加商品,在此时需要判断添加的商品是否已经存在,如果存在需要删除
                            if shop_add in shop_value:
                                product_list.pop(shop_index)
                            else:
                                pass

                        list_add = input('the cost of production:')               #当判断不为q或者d后,才会显示商品价格
                        if list_add.isdigit() and shop_add.isalnum():             #判断商品价格为数字类型
                            list_add = int(list_add)
                            if list_add > 0:                                      #需要商品价格大于0
                                shop_add_list = (shop_add,list_add)
                                product_list.append(shop_add_list)
                            else:
                                print('list_add must more than zero!!')
                        else:
                            print('please input the right production!')

            elif add_choice == 'Sub':                                              #选择该项表示需要删除商品
                while True:
                    for k,v in enumerate(product_list):
                            print(k,end='')
                            print('.',end=' ')
                            for i in v:
                                print(i,end=' ')
                            print('\n')
                    sub_choice = input('please choice your want to remove production: ')  
                    if sub_choice.isdigit():                                        #判断输入的删除标记位是否为数字类型
                        sub_choice = int(sub_choice)
                        if sub_choice < len(product_list) and sub_choice >= 0:     #判断删除的商品是否存在
                            product_list.pop(sub_choice)
                        else:
                            print('the number is not right,pls input again!')
                    elif sub_choice == 'd':
                        for b in product_list:
                            with open('product.txt','w') as files:
                                files.write(b[0])
                                files.write(' ')
                                files.write(str(b[1]))
                                files.write('\n')
                        break
                    elif sub_choice == 'q':
                        for b in product_list:
                            with open('product.txt','w') as files:
                                files.write(b[0])
                                files.write(' ')
                                files.write(str(b[1]))
                                files.write('\n')
                        exit('end of adding the production-list')
                    else:
                        print('wront remove option,please choice again!')

            elif add_choice == 'd':                                             #卖家登录状态后,如果需要到上一层目录,需要此时将已添加的商品存入文件中
                for i in product_list:
                    with open('product.txt','w') as files:
                        files.write(i[0])
                        files.write(' ')
                        files.write(str(i[1]))
                        files.write('\n')
                break
            elif add_choice == 'q':                                             #卖家登录状态后,如果需要退出程序,需要此时将已添加的商品存入文件中
                for i in product_list:
                     with open('product.txt','w') as files:
                        files.write(i[0])
                        files.write(' ')
                        files.write(str(i[1]))
                        files.write('\n')
                exit('end of adding the production-list')
            else:
                print('wrong add production option,please input again!')


    elif choice_key == 'q':
        exit('ending the shopping')
    else:
        print('wrong input! please choice again')

 

   

posted on 2017-01-19 11:20  爱python的小皮  阅读(1079)  评论(0编辑  收藏  举报