Home > Back-end >  Python: Avoiding for-loop in combination with range
Python: Avoiding for-loop in combination with range

Time:12-21

I got an input function to choose products out of an entered input number of products with some error handling. For this, I used a for loop in combination with range, which is not very pythonic, as it should be possible to iterate over without using range, but unfortunately, I didn't manage. So this is (part of my) code:

valid_expression = False # for next while loop
    while valid_expression is False:
        products = []

        for i in range(no_of_products_sel):
            products_confirmed = False # for next while loop
            while products_confirmed is False:
                product = input(f"Please enter product name {i 1}:")
                if product.lower().strip() == "exit":
                    print("See you soon!")
                    return None
                product_clean = product.lower().title().strip()
                if product_clean in products:
                    print(f"Already chosen! Choose another product!")

                elif product_clean in list_of_products:
                    products.append(product_clean)
                    products_codes[product_clean]=product_codes(product)  # get product codes, save them in dict
                    product_confirmed = True

                elif product_clean not in list_of_products:
                    print(f"\n---\nYou have entered '{product}', which is not in the stock. Enter another product!\n---\n")

            valid_expression = True

How can I avoid the combination of for-loop and range in for i in range(no_of_products_sel):?

CodePudding user response:

You can avoid using the combination of a for loop and range by using a while loop instead. Here's an example of how you can modify the code to use a while loop:

products = []
i = 0

while i < no_of_products_sel:
    product_confirmed = False
    while not product_confirmed:
        product = input(f"Please enter product name {i 1}:")
        if product.lower().strip() == "exit":
            print("See you soon!")
            return None

        product = product.lower().title().strip()
        if product in products:
            print("Already chosen! Choose another product!")
        elif product not in list_of_products:
            print(f"\n---\nYou have entered '{product}', which is not in the stock. Enter another product!\n---\n")
        else:
            products.append(product)
            products_codes[product] = product_codes(product)
            product_confirmed = True
            i  = 1

Note: I removed the outer while loop and the valid_expression variable, since they don't seem to serve any purpose in the code unless you need them.

  • Related