1. 程式人生 > 其它 >跟別人學習的一個小程度,雖然有點不完美,希望大家提出一些意見

跟別人學習的一個小程度,雖然有點不完美,希望大家提出一些意見

------------恢復內容開始------------

!/usr/bin/python

-- coding: UTF-8 --

需求:

1.啟動程式後,讓使用者輸入工資,然後列印商品列表

2.允許使用者根據商品編號購買商品

3.使用者選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒

4.可隨時退出,退出時,列印已購買商品和餘額

定義商品列表

product_list = [[1,"Iphone", 5999],[2,"Ipadmin",3999],[3,"Airpods",999],[4,"Apple watch",1999],[5,"Coffe",29],[6,"Book",89]]

購物清單

shopping_list = [] # 空列表,存放購買的商品
salary = int(input("Please enter your salary:")) # 輸入工資
while True :
for i in product_list: # 列印列表
print(i)
choice_product_number = input("Please enter the product number you want:") # 選擇商品編號
if choice_product_number.isdigit(): # 判定 choice_product_number 是否為數值
choice_product_number = int(choice_product_number)
if choice_product_number-1 < len(product_list) and choice_product_number-1 >= 0 : # 判定使用者輸入的編號是否合理
product_choice = product_list[choice_product_number-1]
if product_choice[2] < salary : # 判定是否買得起
shopping_list.append(product_choice) # 買得起,就放入購物車
salary -= product_choice[2] # 賦值運算子 salary = salary - product_choice[2]
print("Add %s into your shopping_list,your balance is \033[31;1m %s \033[0m" % (product_choice, salary)) # \033[31;1m%s\033[0m 控制高亮顯示的程式碼,需要死記硬背,沒有捷徑,多寫程式碼自然就記住了 31代表高亮顏色
else:
print("\033[41;1mYou have %s left!Not enough!!!\033[0m" % salary)
print("---------shopping list-----------")
for s in shopping_list:
print(s)
print("---------shopping list-----------")
print("你的餘額為:\033[31;1m%s\033[0m" % salary)
else:
print("沒有這個商品")
elif choice_product_number == "q":
print("---------shopping list-----------")
for s in shopping_list:
print(s)
print("---------shopping list-----------")
print("你的餘額為:\033[31;1m%s\033[0m"%salary)
exit()
else:
print("輸入錯誤")
------------恢復內容結束------------