數據類型、字符編碼、文件處理


一 引子

1 什么是數據?

  x=10,10是我們要存儲的數據

2 為何數據要分不同的類型

  數據是用來表示狀態的,不同的狀態就應該用不同的類型的數據去表示

3 數據類型

  數字(整形,長整形,浮點型,復數)

  字符串

  字節串:在介紹字符編碼時介紹字節bytes類型

  列表

  元組

  字典

  集合

4 按照以下幾個點展開數據類型的學習

#======================================基本使用======================================
#1、用途

#2、定義方式

#3、常用操作+內置的方法

#======================================該類型總結====================================
#存一個值or存多個值
    
#有序or無序

#可變or不可變(1、可變:值變,id不變。可變==不可hash 2、不可變:值變,id就變。不可變==可hash)

二 數字

整型與浮點型

#整型int
  作用:年紀,等級,身份證號,qq號等整型數字相關
  定義:
    age=10 #本質age=int(10)

#浮點型float
  作用:薪資,身高,體重,體質參數等浮點數相關

    salary=3000.3 #本質salary=float(3000.3)

#二進制,十進制,八進制,十六進制 

其他數字類型(了解)

#長整形(了解)
    在python2中(python3中沒有長整形的概念):      
    >>> num=2L
    >>> type(num)
    <type 'long'>

#復數(了解,推薦視頻:https://www.bilibili.com/video/av26786159)  
    >>> x=1-2j
    >>> x.real
    1.0
    >>> x.imag
    -2.0  

三 字符串

#作用:名字,性別,國籍,地址等描述信息

#定義:在單引號\雙引號\三引號內,由一串字符組成
name='egon'

#優先掌握的操作:
#1、按索引取值(正向取+反向取) :只能取
#2、切片(顧頭不顧尾,步長)
#3、長度len
#4、成員運算in和not in

#5、移除空白strip
#6、切分split
#7、循環

  需要掌握的操作

#1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三種玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit
#strip
name='*egon**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*'))

#lower,upper
name='egon'
print(name.lower())
print(name.upper())

#startswith,endswith
name='alex_SB'
print(name.endswith('SB'))
print(name.startswith('alex'))

#format的三種玩法
res='{} {} {}'.format('egon',18,'male')
res='{1} {0} {1}'.format('egon',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)

#split
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默認分隔符為空格
name='C:/a/b/c/d.txt' #只想拿到頂級目錄
print(name.split('/',1))

name='a|b|c'
print(name.rsplit('|',1)) #從右開始切分

#join
tag=' '
print(tag.join(['egon','say','hello','world'])) #可迭代對象必須都是字符串

#replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1))

#isdigit:可以判斷bytes和unicode類型,是最常用的用於於判斷字符是否為"數字"的方法
age=input('>>: ')
print(age.isdigit())
示例

 其他操作(了解即可)

#1、find,rfind,index,rindex,count
#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is數字系列
#6、is其他
#find,rfind,index,rindex,count
name='egon say hello'
print(name.find('o',1,3)) #顧頭不顧尾,找不到則返回-1不會報錯,找到了則顯示索引
# print(name.index('e',2,4)) #同上,但是找不到會報錯
print(name.count('e',1,3)) #顧頭不顧尾,如果不指定范圍則查找所有

#center,ljust,rjust,zfill
name='egon'
print(name.center(30,'-'))
print(name.ljust(30,'*'))
print(name.rjust(30,'*'))
print(name.zfill(50)) #用0填充

#expandtabs
name='egon\thello'
print(name)
print(name.expandtabs(1))

#captalize,swapcase,title
print(name.capitalize()) #首字母大寫
print(name.swapcase()) #大小寫翻轉
msg='egon say hi'
print(msg.title()) #每個單詞的首字母大寫

#is數字系列
#在python3中
num1=b'4' #bytes
num2=u'4' #unicode,python3中無需加u就是unicode
num3='' #中文數字
num4='' #羅馬數字

#isdigt:bytes,unicode
print(num1.isdigit()) #True
print(num2.isdigit()) #True
print(num3.isdigit()) #False
print(num4.isdigit()) #False

#isdecimal:uncicode
#bytes類型無isdecimal方法
print(num2.isdecimal()) #True
print(num3.isdecimal()) #False
print(num4.isdecimal()) #False

#isnumberic:unicode,中文數字,羅馬數字
#bytes類型無isnumberic方法
print(num2.isnumeric()) #True
print(num3.isnumeric()) #True
print(num4.isnumeric()) #True

#三者不能判斷浮點數
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
總結:
    最常用的是isdigit,可以判斷bytes和unicode類型,這也是最常見的數字應用場景
    如果要判斷中文數字或羅馬數字,則需要用到isnumeric
'''

#is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或數字組成
print(name.isalpha()) #字符串只由字母組成

print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle())
示例

 

    練習   

# 寫代碼,有如下變量,請按照要求實現每個功能 (共6分,每小題各0.5分)
name = " aleX"
# 1)    移除 name 變量對應的值兩邊的空格,並輸出處理結果
# 2)    判斷 name 變量對應的值是否以 "al" 開頭,並輸出結果# 3)    判斷 name 變量對應的值是否以 "X" 結尾,並輸出結果# 4)    將 name 變量對應的值中的 “l” 替換為 “p”,並輸出結果
# 5)    將 name 變量對應的值根據 “l” 分割,並輸出結果。
# 6)    將 name 變量對應的值變大寫,並輸出結果# 7)    將 name 變量對應的值變小寫,並輸出結果# 8)    請輸出 name 變量對應的值的第 2 個字符?
# 9)    請輸出 name 變量對應的值的前 3 個字符?
# 10)    請輸出 name 變量對應的值的后 2 個字符?# 11)    請輸出 name 變量對應的值中 “e” 所在索引位置?# 12)    獲取子序列,去掉最后一個字符。如: oldboy 則獲取 oldbo。
# 寫代碼,有如下變量,請按照要求實現每個功能 (共6分,每小題各0.5分)
name = " aleX"
# 1)    移除 name 變量對應的值兩邊的空格,並輸出處理結果
name = ' aleX'
a=name.strip()
print(a)

# 2)    判斷 name 變量對應的值是否以 "al" 開頭,並輸出結果
name=' aleX'
if name.startswith(name):
    print(name)
else:
    print('no')

# 3)    判斷 name 變量對應的值是否以 "X" 結尾,並輸出結果
name=' aleX'
if name.endswith(name):
    print(name)
else:
    print('no')

# 4)    將 name 變量對應的值中的 “l” 替換為 “p”,並輸出結果
name=' aleX'
print(name.replace('l','p'))

# 5)    將 name 變量對應的值根據 “l” 分割,並輸出結果。
name=' aleX'
print(name.split('l'))

# 6)    將 name 變量對應的值變大寫,並輸出結果
name=' aleX'
print(name.upper())

# 7)    將 name 變量對應的值變小寫,並輸出結果
name=' aleX'
print(name.lower())

# 8)    請輸出 name 變量對應的值的第 2 個字符?
name=' aleX'
print(name[1])

# 9)    請輸出 name 變量對應的值的前 3 個字符?
name=' aleX'
print(name[:3])

# 10)    請輸出 name 變量對應的值的后 2 個字符?
name=' aleX'
print(name[-2:])

# 11)    請輸出 name 變量對應的值中 “e” 所在索引位置?
name=' aleX'
print(name.index('e'))

# 12)    獲取子序列,去掉最后一個字符。如: oldboy 則獲取 oldbo。
name=' aleX'
a=name[:-1]
print(a)
View Code    

四 列表

#作用:多個裝備,多個愛好,多門課程,多個女朋友等

#定義:[]內可以有多個任意類型的值,逗號分隔
my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本質my_girl_friends=list([...])
或
l=list('abc')

#優先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取      
#2、切片(顧頭不顧尾,步長)
#3、長度
#4、成員運算in和not in

#5、追加
#6、刪除
#7、循環
#ps:反向步長
l=[1,2,3,4,5,6]

#正向步長
l[0:3:1] #[1, 2, 3]
#反向步長
l[2::-1] #[3, 2, 1]
#列表翻轉
l[::-1] #[6, 5, 4, 3, 2, 1]

  

    練習:

1. 有列表data=['alex',49,[1900,3,18]],分別取出列表中的名字,年齡,出生的年,月,日賦值給不同的變量

2. 用列表模擬隊列

3. 用列表模擬堆棧

4. 有如下列表,請按照年齡排序(涉及到匿名函數)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]
答案:
l.sort(key=lambda item:item['age'])
print(l)

五 元組

#作用:存多個值,對比列表來說,元組不可變(是可以當做字典的key的),主要是用來讀

#定義:與列表類型比,只不過[]換成()
age=(11,22,33,44,55)本質age=tuple((11,22,33,44,55))

#優先掌握的操作:
#1、按索引取值(正向取+反向取):只能取   
#2、切片(顧頭不顧尾,步長)
#3、長度
#4、成員運算in和not in

#5、循環

 

  練習

#簡單購物車,要求如下:
實現打印商品詳細信息,用戶輸入商品名和購買個數,則將商品名,價格,購買個數加入購物列表,如果輸入為空或其他非法輸入則要求用戶重新輸入  

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
} 
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods_l=[]
while True:
    for key,item in msg_dic.items():
        print('name:{name} price:{price}'.format(price=item,name=key))
    choice=input('商品>>: ').strip()
    if not choice or choice not in msg_dic:continue
    count=input('購買個數>>: ').strip()
    if not count.isdigit():continue
    goods_l.append((choice,msg_dic[choice],count))

    print(goods_l)
View Code

六 字典

#作用:存多個值,key-value存取,取值速度快

#定義:key必須是不可變類型,value可以是任意類型
info={'name':'egon','age':18,'sex':'male'} #本質info=dict({....})
或
info=dict(name='egon',age=18,sex='male')
或
info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)

#優先掌握的操作:
#1、按key存取值:可存可取
#2、長度len
#3、成員運算in和not in

#4、刪除
#5、鍵keys(),值values(),鍵值對items()
#6、循環

 

  練習

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中

即: {'k1': 大於66的所有值, 'k2': 小於66的所有值}
a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
    if i>66:
        a['k1'].append(i)
    else:
        a['k2'].append(i)
print(a)
View Code
2 統計s='hello alex alex say hello sb sb'中每個單詞的個數

結果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
s='hello alex alex say hello sb sb'

l=s.split()
dic={}
for item in l:
    if item in dic:
        dic[item]+=1
    else:
        dic[item]=1
print(dic)
View Code
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
print(words)
for word in words: #word='alex'
    dic[word]=s.count(word)
    print(dic)


#利用setdefault解決重復賦值
'''
setdefault的功能
1:key存在,則不賦值,key不存在則設置默認值
2:key存在,返回的是key對應的已有的值,key不存在,返回的則是要設置的默認值
d={}
print(d.setdefault('a',1)) #返回1

d={'a':2222}
print(d.setdefault('a',1)) #返回2222
'''
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
    dic.setdefault(word,s.count(word))
    print(dic)



#利用集合,去掉重復,減少循環次數
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
words_set=set(words)
for word in words_set:
    dic[word]=s.count(word)
    print(dic)
其他做法(重點看setdefault的用法)

七 集合 

#作用:去重,關系運算,

#定義:
            知識點回顧
            可變類型是不可hash類型
            不可變類型是可hash類型

#定義集合:
            集合:可以包含多個元素,用逗號分割,
            集合的元素遵循三個原則:
             1:每個元素必須是不可變類型(可hash,可作為字典的key)
             2:沒有重復的元素
             3:無序

注意集合的目的是將不同的值存放到一起,不同的集合間用來做關系運算,無需糾結於集合中單個值
 

#優先掌握的操作:
#1、長度len
#2、成員運算in和not in

#3、|合集
#4、&交集
#5、-差集
#6、^對稱差集
#7、==
#8、父集:>,>= 
#9、子集:<,<=

 

    練習

  一.關系運算
  有如下兩個集合,pythons是報名python課程的學員名字集合,linuxs是報名linux課程的學員名字集合
  pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
  linuxs={'wupeiqi','oldboy','gangdan'}
  1. 求出即報名python又報名linux課程的學員名字集合
  2. 求出所有報名的學生名字集合
  3. 求出只報名python課程的學員名字
  4. 求出沒有同時這兩門課程的學員名字集合
# 有如下兩個集合,pythons是報名python課程的學員名字集合,linuxs是報名linux課程的學員名字集合
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
# 求出即報名python又報名linux課程的學員名字集合
print(pythons & linuxs)
# 求出所有報名的學生名字集合
print(pythons | linuxs)
# 求出只報名python課程的學員名字
print(pythons - linuxs)
# 求出沒有同時這兩門課程的學員名字集合
print(pythons ^ linuxs)
View Code
   二.去重

   1. 有列表l=['a','b',1,'a','a'],列表元素均為可hash類型,去重,得到新列表,且新列表無需保持列表原來的順序

   2.在上題的基礎上,保存列表原來的順序

   3.去除文件中重復的行,肯定要保持文件內容的順序不變
   4.有如下列表,列表元素為不可hash類型,去重,得到新列表,且新列表一定要保持列表原來的順序

l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]  
#去重,無需保持原來的順序
l=['a','b',1,'a','a']
print(set(l))

#去重,並保持原來的順序
#方法一:不用集合
l=[1,'a','b',1,'a']

l1=[]
for i in l:
    if i not in l1:
        l1.append(i)
print(l1)
#方法二:借助集合
l1=[]
s=set()
for i in l:
    if i not in s:
        s.add(i)
        l1.append(i)

print(l1)


#同上方法二,去除文件中重復的行
import os
with open('db.txt','r',encoding='utf-8') as read_f,\
        open('.db.txt.swap','w',encoding='utf-8') as write_f:
    s=set()
    for line in read_f:
        if line not in s:
            s.add(line)
            write_f.write(line)
os.remove('db.txt')
os.rename('.db.txt.swap','db.txt')

#列表中元素為可變類型時,去重,並且保持原來順序
l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]
# print(set(l)) #報錯:unhashable type: 'dict'
s=set()
l1=[]
for item in l:
    val=(item['name'],item['age'],item['sex'])
    if val not in s:
        s.add(val)
        l1.append(item)

print(l1)






#定義函數,既可以針對可以hash類型又可以針對不可hash類型
def func(items,key=None):
    s=set()
    for item in items:
        val=item if key is None else key(item)
        if val not in s:
            s.add(val)
            yield item

print(list(func(l,key=lambda dic:(dic['name'],dic['age'],dic['sex']))))
View Code

八 數據類型總結

按存儲空間的占用分(從低到高)

數字
字符串
集合:無序,即無序存索引相關信息
元組:有序,需要存索引相關信息,不可變
列表:有序,需要存索引相關信息,可變,需要處理數據的增刪改
字典:無序,需要存key與value映射的相關信息,可變,需要處理數據的增刪改

按存值個數區分

標量/原子類型 數字,字符串
容器類型 列表,元組,字典

 

 

按可變不可變區分

可變 列表,字典
不可變 數字,字符串,元組

 

 

按訪問順序區分

直接訪問 數字
順序訪問(序列類型) 字符串,列表,元組
key值訪問(映射類型) 字典

 

 

  

九 運算符

#身份運算(is ,is not)
is比較的是id,而雙等號比較的是值
毫無疑問,id若相同則值肯定相同,而值相同id則不一定相同
>>> x=1234567890
>>> y=1234567890
>>> x == y
True
>>> id(x),id(y)
(3581040, 31550448)
>>> x is y
False

詳細:http://www.cnblogs.com/linhaifeng/articles/5935801.html#_label34

十 字符編碼

http://www.cnblogs.com/linhaifeng/articles/5950339.html 

十一 文件處理

http://www.cnblogs.com/linhaifeng/articles/5984922.html

十二 作業

#作業一: 三級菜單
#要求:
打印省、市、縣三級菜單
可返回上一級
可隨時退出程序
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '網易':{},
                'google':{}
            },
            '中關村':{
                '愛奇藝':{},
                '汽車之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龍觀':{},
        },
        '朝陽':{},
        '東城':{},
    },
    '上海':{
        '閔行':{
            "人民廣場":{
                '炸雞店':{}
            }
        },
        '閘北':{
            '火車戰':{
                '攜程':{}
            }
        },
        '浦東':{},
    },
    '山東':{},
}



tag=True
while tag:
    menu1=menu
    for key in menu1: # 打印第一層
        print(key)

    choice1=input('第一層>>: ').strip() # 選擇第一層

    if choice1 == 'b': # 輸入b,則返回上一級
        break
    if choice1 == 'q': # 輸入q,則退出整體
        tag=False
        continue
    if choice1 not in menu1: # 輸入內容不在menu1內,則繼續輸入
        continue

    while tag:
        menu_2=menu1[choice1] # 拿到choice1對應的一層字典
        for key in menu_2:
            print(key)

        choice2 = input('第二層>>: ').strip()

        if choice2 == 'b':
            break
        if choice2 == 'q':
            tag = False
            continue
        if choice2 not in menu_2:
            continue

        while tag:
            menu_3=menu_2[choice2]
            for key in menu_3:
                print(key)

            choice3 = input('第三層>>: ').strip()
            if choice3 == 'b':
                break
            if choice3 == 'q':
                tag = False
                continue
            if choice3 not in menu_3:
                continue

            while tag:
                menu_4=menu_3[choice3]
                for key in menu_4:
                    print(key)

                choice4 = input('第四層>>: ').strip()
                if choice4 == 'b':
                    break
                if choice4 == 'q':
                    tag = False
                    continue
                if choice4 not in menu_4:
                    continue

                # 第四層內沒數據了,無需進入下一層
三級菜單面條版 
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '網易':{},
                'google':{}
            },
            '中關村':{
                '愛奇藝':{},
                '汽車之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龍觀':{},
        },
        '朝陽':{},
        '東城':{},
    },
    '上海':{
        '閔行':{
            "人民廣場":{
                '炸雞店':{}
            }
        },
        '閘北':{
            '火車戰':{
                '攜程':{}
            }
        },
        '浦東':{},
    },
    '山東':{},
}



#part1(初步實現):能夠一層一層進入
layers = [menu, ]

while True:
    current_layer = layers[-1]
    for key in current_layer:
        print(key)

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

    if choice not in current_layer: continue

    layers.append(current_layer[choice])



#part2(改進):加上退出機制
layers=[menu,]

while True:
    if len(layers) == 0: break
    current_layer=layers[-1]
    for key in current_layer:
        print(key)

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

    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break

    if choice not in current_layer:continue

    layers.append(current_layer[choice])
三級菜單文藝青年版
#作業二:請閉眼寫出購物車程序
#需求:
用戶名和密碼存放於文件中,格式為:egon|egon123
啟動程序后,先登錄,登錄成功則讓用戶輸入工資,然后打印商品列表,失敗則重新登錄,超過三次則退出程序
允許用戶根據商品編號購買商品
用戶選擇商品后,檢測余額是否夠,夠就直接扣款,不夠就提醒
可隨時退出,退出時,打印已購買商品和余額
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')
購物車程序面條版

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM