python 購物車程式

來源:互聯網
上載者:User

標籤:取出   方法   dex   ike   ==   判斷   字串   輸入   exit   

購物車程式編寫方式;

1、首先將其所有的商品列出來,然後在建立一個空列表,用於存放所購買的的商品

2、輸入使用者的工資,在進行判斷輸入的是否為數字,如果不是,退出如果是繼續執行

3、進入到一個死迴圈while True:

4、將所有商品列出來,在通過enumerate 在將其下標取出

5、讓使用者輸入所要購買商品的代號數字,並判斷使用者輸入的是否為數字

6、再判斷是否為 q 退出,如果為q則列印所購買上的商品,並顯示餘額,如果不是則通過print提示 輸入錯誤(invaild  option),並重新輸入

7、如果使用者所選擇的為數字,在判斷數字是否在0和所列出的商品之中通過 len()判斷

8、如果在所選商品的範圍內,在進行工資的判斷,查看是否購買的起,如果可以購買,通過append 添加再將其添加到空列表中去

9、一直迴圈到使用者輸入q或者餘額不夠為止

10、然後通過print將其輸出即可

程式如下:

#首先通過列表將產品進行列出
product_list = [
    ("iphone",5800),
    ("moc pro",9800),
    ("bike",800),
    ("coffee",31),
    ("linux book",80)
]
shopping_list =[]
salary = input("input your salary:")
if salary.isdigit(): # 用於判斷輸入的字串是否為數字形式  如果為是則為真
    salary = int(salary)
    while True:
       # for item in  product_list: #for item in range product_list: 寫法錯誤
           # 方式一: print(product_list.index(item),item) #通過 index 將其下標顯示出來用於產品編號
        for index,item in enumerate(product_list): #  方法二:index表示下標   item 表示enumerate 中的列表 資料
            print(index,item)
        user_choice = input("please input your  want to  buy thing:")
        if user_choice.isdigit():
            user_choice =int(user_choice)
            if user_choice<len(product_list)and user_choice>=0:
                p_item =product_list[user_choice] #將使用者選擇的商品的下標取出來
                if  p_item[1] <=salary :# 將使用者選擇出來的商品與使用者的工資進行比較   小於工資表示買的起
                    shopping_list.append(p_item)
                    salary -=p_item[1]
                    print("added %s into shopping cart,your balance \033[31;1m%s\033[0m"%(p_item,salary))                # %s預留位置使用時,不能用逗號將其前後分    開,\033[31;1m%s\033[0m  表示將最後一個預留位置所表示的數值進行顏色的設定                                                                                                                                 
                else:
                    print("\033[41;1m你的餘額只剩%s啦,買不起了\033[0m"%salary)
            else:
                print("product [%s] is not exist!"%user_choice)
        elif user_choice ==‘q‘:
            print("-------------shopping list-----------")
            for p in shopping_list:
                print(p)
            print("your  current balance:",salary)
            exit()
        else:
            print("invaild  option.....")

python 購物車程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.