題目來源:老男孩教育Python視頻
# -*- coding: utf-8 -*-
"""
@Author:yhf1995
@time:2020/1/30 8:24
"""
salary = input("Please input your money number:")
product_list =[
("Apple watch", 4500),
("milk", 60),
("bike", 1000),
("Starbucks", 40),
("book",80)
]
shopping_list = []
if salary.isdigit():
salary = int(salary)
# 判斷輸入的金額是否爲數字,如果是將其轉爲int類型,如果不是,輸出 輸入有誤
while True:
for item in product_list:
print(product_list.index(item),item)
# 打印商品列表
choice_number = input("Please enter the number of the product you want:>>>")
if choice_number.isdigit():
choice_number = int (choice_number)
# 判斷輸入的商品編號是否爲數字,如果是轉爲int型,如果不是,提示輸入有誤
if choice_number < len(product_list) and choice_number >= 0:
# 判斷商品是否存在
if salary >= product_list[choice_number][1]:
shopping_list.append(product_list[choice_number])
salary -= product_list[choice_number][1]
print("add shop %s in your shopping cart,and your salary is \033[31;1m%s\033[0m!"%(product_list[choice_number],salary))
# 判斷餘額是否足夠,餘額足夠,將商品放入購物車,餘額減去該商品價格,輸出放入購物車的商品和餘額
else:
print("You have insufficient balance!")
# 餘額不足
else:
print("product_number does not exist!")
# 商品不存在
elif choice_number == "Q":
print("The shopping cart list is as follows:")
for shop_item in shopping_list:
print(shop_item)
print("Your current balance is %s."%(salary))
exit()
# 輸入Q 打印購物車商品和餘額,並退出購物車程序
else:
print("The product_number is error!")
# 商品編號有誤
else:
print("The amount entered is not a number!")
# 金額有誤
這是學習老男孩教育Python課程的一個記錄,我覺得該課程講的挺好的。可參考金角大王Python之路02。