Anya Anya - 1 month ago 9
Python Question

How to find and print out of a specific value from a list (at least i think thats what i want to do?)

Here is my code:

n = 1
inputs = []
quantities = []
while n == 1:
w = input('Enter the product code: ')
inputs.append(w)
with open('items.txt') as f:
found = False
for line in f:
if w in line:
price1 = line[21:25]
desc1 = line[9:17]
quantity1 = line[18:20]
print(desc1)
print('Price = ' +str(price1))
print('Available Quantity = ' +str(quantity1))

if n == 0:
print('And your products are: ')
for i in inputs:
with open('items.txt') as f:
for line in f:
if i in line:
desc1 = line[9:17]
price1 = line[21:25]
print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities))


There is no error when running the code. When run, it outputs:

Our available products are:
15372185 ChocBisc
13281038 AppJuice
26419633 TomaSoup
74283187 SprRolls
Enter the product code: 74283187
SprRolls
Price = 0.90
Available Quantity = 86
Is this what you want? (Y/N) y
How much would you like? 34
Would you like to continue? (Y/N) y
Continuing!
Enter the product code: 15372185
ChocBisc
Price = 1.20
Available Quantity = 50
Is this what you want? (Y/N) y
How much would you like? 45
Would you like to continue? (Y/N) n
System Closing!
And your products are:
SprRolls 0.90 [34, 45]
ChocBisc 1.20 [34, 45]


As you can see, right at the bottom, it prints both quantities entered. I knew it was going to do this but i dont know how to rectify it. What i need it to do is to print only the quantity entered for that product code. Any help as always would be greatly appreciated. Thank you!!

Also i removed most of the script under while n == 1 since this is my coursework, and i would rather it didn't get copied or anything like that. Hopefully this still shows the relevant section of the code to the question.

Answer

I would re-write the latter part of your code to iterate through the range of values in inputs, rather than the values themselves. Then, you can call the index of the element you want to print from quantities.

As a caveat, this works in your case because the user send inputs to inputs one at a time (so, the indices of inputs correspond with the indices of quantities). You might consider a different data structure to use within this code, like a dictionary, which could store product codes and quantities as key/value pairs. Then, you can simply refer to the key of the dictionary when printing.

Here is how I would suggest changing your code:

if n == 0:
    print('And your products are: ')
    for i in range(len(inputs)):
        with open('items.txt') as f: 
            for line in f:
                if inputs[i] in line:
                    desc1 = line[9:17]
                    price1 = line[21:25]
                    print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities[i]))