创建自动售货机程序:用户可以选择相应商品代表的数字(1,2,3,4...),根据不同的商品系统提示不同的商品价格
时间: 2024-09-27 08:03:06 浏览: 36
创建一个简单的自动售货机程序可以分为以下几个步骤:
1. **初始化商品信息**:先定义一个商品列表,每个商品对应一个数字ID和价格。例如:
```python
products = {
1: {"name": "饮料", "price": 5},
2: {"name": "巧克力", "price": 3},
3: {"name": "薯片", "price": 4},
# 添加更多商品...
}
```
2. **获取用户输入**:设计一个函数接收用户的输入,比如整数选择:
```python
def get_user_choice():
while True:
choice_str = input("请输入你想购买的商品编号(1-{}): ".format(len(products)))
if choice_str.isdigit() and 1 <= int(choice_str) <= len(products):
return int(choice_str)
else:
print("无效的选择,请重新输入。")
```
3. **处理用户选择**:
```python
def handle_purchase(choice):
product_info = products.get(choice)
if product_info:
price = product_info["price"]
print(f"你要购买的是{product_info['name']}, 价格为{price}元。确认购买吗?")
confirm = input("y/n: ")
if confirm.lower() == 'y':
return price
else:
print("购买取消.")
else:
print("商品不存在.")
# 主程序循环
while True:
choice = get_user_choice()
purchase_price = handle_purchase(choice)
if purchase_price:
# 支付逻辑(这里仅示例)
print("支付成功,找零...")
```
在这个例子中,用户通过输入数字选择商品,系统会显示商品名和价格,并询问是否确认购买。如果选择有效,程序将继续运行支付流程。
阅读全文
相关推荐

















