在本题中,我们将利用所学的字典以及 for
循环、if else
语句尝试设计一个购物车系统。
我们会在代码框里给出所有商品的信息,如下所示:
goods = [
{"name": "Computer", "price": 1999},
{"name": "Mouse", "price": 10},
{"name": "Yachts", "price": 20},
{"name": "Airplane", "price": 998}
]
请在代码框内编写你的代码,
其中 main.py
中的 asset
表示用户当前资产(为正整数), input_list
为用户在接下来的过程中输入的列表。
输入列表由包括 0 的正整数表示,比如 input_list = [0, 2, 4, 5, 1, 0]
,购买行为按照以下规则执行:
- 如果输入为 0 则表示结束当前购买;
- 输入序列为 1、2、3、4 分别对应商品列表对应位置的商品(索引从 1 开始),如果商品价格小于等于用户当前资产,则输出
"Purchase successful!"
,并从用户当前资产中扣除商品价格,重新读入输入;如果商品价格超过用户当前资产,则输出"The balance is low, so go ahead and top up!"
,并结束当前购买; - 输入如果大于 4,则提示用户
“Please re-enter”
,并重新读入用户输入。
import sys
# keep the code below
goods = [
{"name": "Computer", "price": 1999},
{"name": "Mouse", "price": 10},
{"name": "Yachts", "price": 20},
{"name": "Airplane", "price": 998}
]
asset = int(sys.argv[1])
input_list = eval(sys.argv[2])
# write your code here
for i in range(0,len(input_list)):
if input_list[i] <= 0:
break
else:
if input_list[i] <= 4:
good_name, good_price = goods[input_list[i]-1]['name'], goods[input_list[i]-1]['price']
print(f'You want to buy: {good_name}')
print(f'It is priced at: {good_price}')
if good_price <= asset:
assset = asset - good_price
print("Purchase successful!")
else:
print("The balance is low, so go ahead and top up!")
break
else:
print("Please re-enter")
continue
注意点:
1.第二个if语句中,即字典引用时,直接将其复制一份,而不是对字典进行修改。且引用格式为:
dict[序列号][属性名]