在Python中,你可以使用以下代码来创建一个简单的购物菜单程序,该程序会要求用户输入工资,然后根据工资显示购物菜单,并允许用户购买商品直到余额不足为止。退出时,程序会打印用户已购买的商品和剩余金额。
```python
!/usr/env python
coding:utf-8
import re
def get_customer_salary():
while True:
salary = input('Please input your monthly salary (a positive integer): ')
if __is_valid_num(salary):
return int(salary)
else:
print('[warn] Please input a valid number!')
def __is_valid_num(num):
p = re.compile(r'^\d+$')
m = p.match(num)
return m is not None
def get_customer_selection(menu, balance):
while True:
selection = input('Please enter the goods number you want to buy or type "exit" to quit: ')
if selection.lower() == 'exit':
break
if __is_valid_num(selection):
if __is_a_valid_selection(int(selection), balance):
return int(selection)
else:
print('[warn] Invalid selection or balance not sufficient.')
else:
print('[warn] Please input a valid number!')
def __is_a_valid_selection(item_number, balance):
This function should be updated with actual menu and pricing information
For demonstration, let's assume the first item costs 10 and the second costs 20
menu_prices = {1: 10, 2: 20}
return menu_prices.get(item_number, 0) <= balance
def display_menu(menu):
print("Shopping Menu:")
for idx, item in enumerate(menu, start=1):
print(f"{idx}. {item['name']}")
print(f"Price: ${item['price']}")
def main():
salary = get_customer_salary()
balance = salary Initially, the balance is the user's salary
menu_items = [
{'name': 'item1', 'price': 10},
{'name': 'item2', 'price': 20},
Add more items as needed
]
display_menu(menu_items)
while balance >= 0:
item_number = get_customer_selection(menu_items, balance)
if item_number is not None:
balance -= menu_items[item_number - 1]['price']
print(f"You have bought {menu_items[item_number - 1]['name']}. Remaining balance: ${balance}")
print("Thank you for shopping! Here is what you have bought:")
for idx, item in enumerate(menu_items, start=1):
if idx in [item_number for item_number in range(1, balance + 1)]:
print(f"{idx}. {item['name']}")
if __name__ == "__main__":
main()
请注意,这个代码示例中的菜单项和价格是硬编码的,你需要根据实际情况更新`menu_items`列表中的数据。此外,`__is_a_valid_selection`函数需要根据实际的菜单和价格信息进行更新,以确保用户的选择是有效的,并且余额足够支付所选商品。
运行这个程序,用户可以输入工资,浏览菜单,并根据菜单提示购买商品。程序会在用户购买商品后更新余额,并在用户退出时打印出用户已购买的商品列表和剩余金额