python實現簡單的購物程序代碼實例
需求:
啟動程序后,讓用戶輸入工資,然后打印商品列表 允許用戶根據商品編號購買商品 用戶選擇商品后,檢測余額是否夠,夠就直接扣款,不夠就提醒 可隨時退出,退出時,打印已購買商品和余額代碼如下
#!/usr/bin/ven python# Author: Hawkeye’’’本程序為實例程序:購物車程序需求:啟動程序后,讓用戶輸入工資,然后打印商品列表允許用戶根據商品編號購買商品用戶選擇商品后,檢測余額是否夠,夠就直接扣款,不夠就提醒可隨時退出,退出時,打印已購買商品和余額’’’#創建商品列表product_list = [ ['Iphone',5800], ['Mac Pro',9800], ['bike',800], ['watch',10600], ['coffee',31], ['Alex Python',20]]# for i in product_list:# print(i)#創建購物列表shopping_list =[]#要求用戶輸入數據salary = input('Input your salary:')#首先要對用戶的輸入做判斷if salary.isdigit(): salary = int(salary) #轉換為整形 while True: #循環輸出列表 for index,item in enumerate(product_list): print(index,item) user_choice = input('請選擇要買什么......') 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 current balance is 033[31;1m%s033[0m' % (p_item,salary) )else:#錢不夠 print('033[41;1m您的余額只剩【%s】,余額不足033[0m' %salary) else:print('033[32;1mProduct code [%s]is not exist033[0m ' %user_choice) elif user_choice == 'q': print('----------shoppig list--------') for p in shopping_list:print(p) print('------------------------------') print('033[33;1mYour current balance is :033[0m',salary) exit() else: print('Invalid Option')else:#輸入q退出 print('033[13;1m【錯誤】請輸入正確的數字!033[0m') exit()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: