1. 程式人生 > >Python 練習:簡單的購物車(二)

Python 練習:簡單的購物車(二)

while purchase .cn iphone AC 圖片 coffee iphone6 信息

優化了上一個購物車程序:http://www.cnblogs.com/klvchen/p/8577269.html

#輸入工資
salary = input("Please input your salary: ")

#判斷工資是否為整數
if salary.isdigit(): salary = int(salary) else: exit("you must input digit")

#定義購物車 cart
= [] #商品信息 msg = [["iphone6s", 5800], ["mac book", 9000], ["coffee", 32], ["bicycle", 1500]] while
True:
  #展示商品信息
for k, v in enumerate(msg, 1): print("%s 商品名稱: %s, 價格: %d" % (k, v[0], v[1])) choice = input("Please select the product number you need to purchase ! [q] to exit")
  #退出
if choice == q: print("========== You have buy ==========") for l in cart:
print(l) exit()
  #選擇商品
if choice.isdigit(): choice = int(choice) if 0 < choice <= len(msg):
       #判斷余額是否充足
if salary >= msg[choice-1][1]: salary -= msg[choice-1][1] print("You have buy %s, money has %d" %(msg[choice-1][0], salary)) cart.append(msg[choice
-1][0]) else: print("You don‘t you enough money! money has %d" %salary ) else: print("Please select right product number!") else: print("Please select right options")

運行結果如下:

技術分享圖片

程序還有很多可以優化的地方,以後有空再琢磨~

Python 練習:簡單的購物車(二)