Python控制台實現簡單的購物車

2021-10-22 07:41:19 字數 3143 閱讀 2786

@[toc]python實現 簡單的控制台 購物車

功能描述:

1、輸入充值金額進行充值,輸出商品清單

2、選擇商品編碼,輸入存在的商品編碼則新增到購物車並顯示餘額,若編碼不存在或輸入格式有誤則提示錯誤並重新輸入。

3、輸入商品編號繼續新增商品,若超出餘額則提示餘額不足。

4、輸入『q』或『q』結束購物,顯示購買的商品清單。

# @author:王家璇

# @file:shopcar.py

# @software:pycharm

products =[[

"iphone"

,5800],

["macpro"

,14000],

["小公尺10"

,3999],

["mate40"

,4999],

["榮耀20s"

,2999]]

#商品清單

shopcar =[0

,0,0

,0,0

,0]#購物車列表,儲存物品的數量

#shopcar = [0 for i in range(6)]

sum=

0#商品總價

count=

0#商品數量

money =

input

("請輸入充值數額:"

)#充值錢包

money =

int(money)

print

("您充值了 %d 元,歡迎開始購物"

%money)

#列印商品列表

print

("-"*5

,"商品列表"

,"-"*5

);for i,item in

enumerate

(products)

:#enumerate函式獲取下標

print

(str

(i)+

"\t"

+item[0]

+"\t"

+str

(item[1]

));#str型別只能連線str型別, int要強制轉換

# for product in products: #for迴圈列印

# print(products.index(product),end="\t")

# for item in product:

# print(item,end="\t")

# print()

while

true:id

=input

("請輸入您要購買的物品的編碼(退出請按q):")if

id.isdigit():

#判斷輸入是否為數字id=

int(id)

;ifid<0or

id>

len(products)-1

:#容錯判斷

print

("\033[1;31m請輸入正確的商品編碼\033[0m");

continue

;else

:if money>=

int(products[id]

[1])

: shopcar[id]

+=1;#購物車中對應商品數量+1

count+=1;

#總數+1

money -=

int(products[id]

[1])

#餘額減少

print

("\033[0;33m您的餘額剩餘%d\033[0m"

%money)

else

:print

("餘額:%d\t\033[1;31m您的餘額不足請重新選擇\033[0m"

%money)

elif

id.isalpha(

)and

id==

"q"or

id==

"q":

if count==0:

print

("您沒有購買任何東西,歡迎下次光臨!");

else

:print

("-"*5

,"購物清單"

,"-"*5

) i=0;

for sumerise in shopcar:

#總計if sumerise!=0:

#將購物車中數量不為零的物品輸出,為零的跳過 i+1繼續遍歷

print

(products[i][0

]+"\t"

+str

(products[i][1

])+"\t"

+"數量:"

+str

(sumerise)

+"個");

sum+=products[i][1

]*sumerise;

i+=1;

print

("總計:%d 件商品 %d 元"

%(count,

sum));

print

("餘額:%d"

%money)

exit();

else

:print

("輸入格式有誤,請輸入數字或q退出系統");

continue

;

清空Python控制台

執行python命令會進入python控制台。在python控制台中可以用互動的方式執行python語句。也就是執行一行python語句,會立刻返回執行結果。當python控制台輸入過多的python語句時,有時需要將這些已經輸入的語句和執行結果清空,並重新開始輸入python語句。例如,下圖就是乙...

沒有控制台視窗的控制台程式

include include pragma comment linker,subsystem windows entry maincrtstartup int main int argc,char argv 編譯後執行程式會彈出乙個訊息框,而沒有背後的控制台視窗。再看看下面的 include in...

Python 控制台進度條的實現

進行爬蟲等耗時的任務時,有時會想在控制台輸出進度條,以顯示當前任務進度。這裡總結了兩種方法。方法1 使用tqdm模組 示例 from time import sleep from tqdm import tqdm for i in tqdm range 1000 sleep 0.005 顯示效果 方...