简体   繁体   中英

How to avoid repetition in conditional statement using a loop?

This is the code I am using to check if the input is a string. itemInput is an input taken from the user. Upon checking if the input matches with the string I append a string from a dictionary to a list. Since it is repetitive, how do I avoid it with a loop?

if itemInput == 'A1':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[0][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[0])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A2':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[1][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[1])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A3':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[2][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[2])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A4':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[3][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[3])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A5':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[4][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[4])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A6':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[5][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[5])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A7':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[6][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[6])))
    additionalitemcategoryPrompt(quantityInput)
elif itemInput == 'A8':
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[7][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[7])))
    additionalitemcategoryPrompt(quantityInput)
dairy_data = {
    'A1': { 'product_name': 'Yogurt', 'price': 2.00 },
    'A2': { 'product_name': 'Milk', 'price': 2.25 },
    'A3': { 'product_name': 'CreamCheese', 'price': 3.50 },
    'A4': { 'product_name': 'FarmerCheese', 'price': 4.75 },
    'A5': { 'product_name': 'BrickCheese', 'price': 6 },
    'A6': { 'product_name': 'SwissCheese', 'price': 8.50 },
    'A7': { 'product_name': 'AmericanCheese', 'price': 7.50 },
    'A8': { 'product_name': 'NachoCheese', 'price': 3.25 },
}


input_item = input('Please enter your item code: ')
# If you want case insensitivity, uncomment this line
# input_item = input_item.upper()

shopping_list = []
if input_item in dairy_data:
    quantity = input('Please state quantity of item: ')
    [product_name, price] = [dairy_data[input_item]['product_name'], dairy_data[input_item]['price']]

    shopping_list.append(f'Product: {product_name} -- Quantity: {quantity} -- Price: {price} $/unit')

You could do a while statement.

dictLen = len(dairyDict)
count = 0
aCount = 1
while count < dictLen:
    if itemInput == f'A{aCount}':
        quantityInput = input('Please state quantity of item: ')
        shoppingList.append('Product:' + str(list(dairyDict.keys())[count][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[count])))
        additionalitemcategoryPrompt(quantityInput)
    count = count +1
    aCount = aCount +1

Something like that would allow you to dynamically go through the dictionary instead of having to write a bunch of elif statements. The while count < dictLen might need to be <=, or it might be correct. I would just try both.

If using Python >= 3.10, you can take advantage of the new pattern matching feature :

itemInput = "A4"

match list(itemInput):
    case ["A", i]:
        i = int(i)
        quantityInput = input('Please state quantity of item: ')
        shoppingList.append('Product:' + str(list(dairyDict.keys())[i-1][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[i-1])))
        additionalitemcategoryPrompt(quantityInput)
    case _:
        print("error")

For earlier versions, use a simple loop to match the input:

itemInput = "A4"

for i in range(8):
    if itemInput == f"A{i+1}":
        quantityInput = input('Please state quantity of item: ')
        shoppingList.append('Product:' + str(list(dairyDict.keys())[i][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[i])))
        additionalitemcategoryPrompt(quantityInput)
        break
else:
    print("error")

Look for the variant part of your code and factor it out. In this case it appears that for A1 you want the first key in the dictionary, and so on. Leaving aside why we're using a dictionary in this case, we can write this very simply:

def get_product(itemInput: str):
    return str(list(dairyDict.keys())[int(itemInput[1]) -1][4:])

Except that (on a horribly long line) you also use the value of the key without truncating it, so you probably just want to get the right key:

def get_product(itemInput: str):
    return list(dairyDict.keys())[int(itemInput[1] - 1)

And then do your truncation, once in your code.

Then you can simply call the fn to get the right part when you build up your message to the user, and only need that code once.

You don't need a loop, just use a regex to validate the input format while saving the number (used as index) with a capture group:

import re

itemInput = "A4"

r = re.match(r"A([1-8])", itemInput)
if r:
    i = int(r.group(1))
    quantityInput = input('Please state quantity of item: ')
    shoppingList.append('Product:' + str(list(dairyDict.keys())[i][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[i])))
    additionalitemcategoryPrompt(quantityInput)
else:
    print("error")

If using Python >= 3.8, you can use the walrus operator to save one line of code:

if r := re.match(r"A([1-8])", itemInput):

Solved it using a loop this way. Thanks for the suggestions!

dairyAlphanumeric = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8']

   for i in range(len(dairyAlphanumeric)):
        if itemInput == 'A' + str(i):
            quantityInput = input('Please state quantity of item: ')
            shoppingList.append('Product:' + str(list(dairyDict.keys())[i-1][4:]) + ' -- Quantity: ' + quantityInput + ' -- Price: $' + '{:.2f}'.format(float(list(dairyDict.values())[i-1])))
            additionalitemcategoryPrompt(quantityInput)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM