Python Shopping Cart - How to use loops to limit certain inputs?

103 Views Asked by At

I'm creating a shopping cart that accepts discounts. How to limit discounts to only be applied once?

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.")

I've spent 2 hours trying to figure it out but am so lost, I've tried setting a class, and defining parameters but can't seem to make it mesh together. I've tried playing around with break, continue and loop statements and for loops but can't figure out why it's not working. You can see that the discount card keeps repeating and allowing the user to enter multiple times.

IDEAL OUTPUT:

Please, enter your choice: 1 Enter 1 to add a discount card. Enter 2 to register a new item. Enter 3 to compute the total and pay. Please, enter your choice: 1

  1. Enter 1, for adding a Pensioner Card
  2. Enter 2, for adding a Weekend Card
  3. Enter 3, for adding a Green Card Please, enter your choice: 1

The Pensioner Card successfully added!

Enter 1 to add a discount card. Enter 2 to register a new item. Enter 3 to compute the total and pay. Please, enter your choice: 1

  1. Enter 1, for adding a Pensioner Card
  2. Enter 2, for adding a Weekend Card
  3. Enter 3, for adding a Green Card Please, enter your choice: 1

Error: Pensioner card has already been applied.

Enter 1 to add a discount card. Enter 2 to register a new item. Enter 3 to compute the total and pay. Please, enter your choice:

ACTUAL OUTPUT:

Please, enter your choice: 1 Enter 1 to add a discount card. Enter 2 to register a new item. Enter 3 to compute the total and pay. Please, enter your choice: 1

  1. Enter 1, for adding a Pensioner Card
  2. Enter 2, for adding a Weekend Card
  3. Enter 3, for adding a Green Card Please, enter your choice: 1

The Pensioner Card successfully added!

Enter 1 to add a discount card. Enter 2 to register a new item. Enter 3 to compute the total and pay. Please, enter your choice: 1

  1. Enter 1, for adding a Pensioner Card
  2. Enter 2, for adding a Weekend Card
  3. Enter 3, for adding a Green Card Please, enter your choice: 1

The Pensioner Card successfully added!

Enter 1 to add a discount card. Enter 2 to register a new item. Enter 3 to compute the total and pay. Please, enter your choice:

2

There are 2 best solutions below

0
AudioBubble On

How to limit discounts to only be applied once?

Like in your code, you need a variable added_discount_cards that keeps track of the added discounts, then just check before adding the discount if it exist in the set, if not, handle the discount and add it to the set.

I made the example in a class, so you can see how it looks when encapsulated.

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'}

        # the following code asks the user input only once
        # you should validate the input in a loop. 
        # Take a look at this question to do it properly

        # 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("Nice try, but this discount is already applied")
            return

        # add the discount to the set so it wont be added again next time            
        self.added_discount_cards.add(discount_choice)
        
        # TODO: implement this function which actually applies the discount
        self.apply_discount(discount_choice)
            
0
alex S On

There are some small edits you can make to your code to make sure that you are only adding a discount card once. I have placed the edited code below and will explain the changes. You have the correct code included but have an order and indentation issue. In this code I moved your last else statement to be under the if statement that checks if a discount has already been applied. If the card has not been added, add it. Else, print the discount has already been applied.

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
        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("Error: Discount card already added.")
    else:
        print("Invalid selection! Please select a Discount Card from the menu.")