我正在创建一个接受折扣的购物车。如何限制折扣只能使用一次?
print("Welcome to the Store!")
print("Enter 1 to start registering your grocery")
print("Enter 2 to close the self-check in register")
selection = input("Please, enter your choice: ")
#Using nested 'while' loops
while selection == '1':
def is_valid_string_input(user_input, valid_choices):
return user_input in valid_choices
print("Enter 1 to add a discount card.")
print("Enter 2 to register a new item.")
print("Enter 3 to compute the total and pay.")
user_choice = input("Please, enter your choice: ")
#Discount cards
added_discount_cards = set()
card_names = {'1': 'Pensioner', '2': 'Weekend', '3': 'Green'}
if user_choice == '1':
print("1. Enter 1, for adding a Pensioner Card")
print("2. Enter 2, for adding a Weekend Card")
print("3. Enter 3, for adding a Green Card")
discount_choice = input("Please, enter your choice: ")
# Validate the user's input for discount cards
if is_valid_string_input(discount_choice, {'1', '2', '3'}):
# Check if the discount card is not added before
for i in range(card_names):
if an
if discount_choice not in added_discount_cards:
added_discount_cards.add(discount_choice)
print(f"The {card_names.get(discount_choice, 'unknown')} Card successfully added!")
else:
print("Invalid selection! Please select a Discount Card from the menu.")
> else:
print("Error: Discount card already added.")
我花了两个小时试图弄清楚它,但我很迷失,我尝试设置一个类,并定义参数,但似乎无法使其啮合在一起。我尝试过使用 Break、Continue 和 Loop 语句以及 for 循环,但不明白为什么它不起作用。可以看到折扣卡不断重复并允许用户多次进入。
理想输出:
请输入您的选择:1 输入 1 添加折扣卡。 输入 2 注册新项目。 输入 3 计算总数并付款。 请输入您的选择:1
养老金领取者卡添加成功!
输入 1 添加折扣卡。 输入 2 注册新项目。 输入 3 计算总数并付款。 请输入您的选择:1
错误:养老金领取者卡已被应用。
输入 1 添加折扣卡。 输入 2 注册新项目。 输入 3 计算总数并付款。 请输入您的选择:
实际输出:
请输入您的选择:1 输入 1 添加折扣卡。 输入 2 注册新项目。 输入 3 计算总数并付款。 请输入您的选择:1
养老金领取者卡添加成功!
输入 1 添加折扣卡。 输入 2 注册新项目。 输入 3 计算总数并付款。 请输入您的选择:1
养老金领取者卡已成功添加!
输入 1 添加折扣卡。 输入 2 注册新项目。 输入 3 计算总数并付款。 请输入您的选择:
如何限制折扣只能使用一次?
就像在您的代码中一样,您需要一个变量
added_discount_cards
来跟踪添加的折扣,然后在添加折扣之前检查它是否存在于集合中,如果不存在,则处理折扣并将其添加到集合中。
我在一个类中做了这个例子,所以你可以看到它封装后的样子。
class ShoppingCart:
def __init__(self):
# initialize the discount cards to empty when Shopping Cart is instantiated
self.added_discount_cards = set()
def add_discount_card(self):
card_names = {'1': 'Pensioner', '2': 'Weekend', '3': 'Green'}
# this asks only once, you should validate the input in a loop,
# exercise for you. Take a look at this question to validate user input
# https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response
print("Select a discount card:")
for key, val in card_names.items():
print(f"{key}: {val}")
discount_choice = input("Please, enter your choice: ")
# here is the part where you check is the discount is already applied
if discount_choice in self.added_discount_cards:
print("Sorry, this discount is already applied")
return
# apply the discount and add it to the set
self.added_discount_cards.add(discount_choice)
# TODO: implement this function
apply_discount(discount_choice)