0

I am writing a code where program read data from file and then it readlines and if a specific word exist in list it allows the user to modify its quantity. Well the issue is how can i get the iteration number (line number) in for loop while it is searching for word in line

My Code:

f= open('guru99.txt','r')

action = int(input('Enter number'))
if action == 1:
    for line in lines:
        if 'banana' in line:
            print(line)
            print('You already purchased banana! You can change the quantity')
            edit = line.split()
            qty = int(input('Enter new quanity'))
            print(bline)
        else:
            continue

for example if the word banana found on line number 3. How to edit this program to show the iteration number or index of the for loop

Noob Saibot
  • 111
  • 7

3 Answers3

1

Add a variable that keeps track of the number of iterations currently passed:

f= open('guru99.txt','r')
lines = f.readlines()
i =1
for line in lines:
    print([i],line)
    i = i+1
count = 0
action = int(input('Enter line number'))
if action == 1:
    for line in lines:
        count += 1
        print(count)
        if 'banana' in line:
            print(line)
            print('You already purchased banana! You can change the quantity')
            edit = line.split()
            qty = int(input('Enter new quanity'))
            edit[-1] = (int(edit[-1]) / float(edit[3]))
            bprice = (edit[-1])
            edit[3] = str(qty)
            edit[-1] = str(int(qty * bprice))
            bline = ' '.join(edit)
            print(bline)
        else:
            continue
0
f= open('guru99.txt','r')
lines = f.readlines()
i =1
line_counter = 0
for line in lines:
    print([i],line)
    i = i+1
    action = int(input('Enter line number'))
    if action == 1:
       for line in lines:
          line_counter += 1
          if 'banana' in line:
             print('You are on line: ' + str(line_counter)
             print('You already purchased banana! You can change the quantity')
             edit = line.split()
             qty = int(input('Enter new quanity'))
             edit[-1] = (int(edit[-1]) / float(edit[3]))
             bprice = (edit[-1])
             edit[3] = str(qty)
             edit[-1] = str(int(qty * bprice))
             bline = ' '.join(edit)
             print(bline)
          else:
             continue
Simeon Ikudabo
  • 1,933
  • 1
  • 7
  • 17
-1

You can try replacing it with a while loop:

i = 0
while i < len(lines):
   # Your code here
   i = i + 1

i is equal to the iteration and lines[i] is equal to the current line.

G. Ross
  • 69
  • 1
  • 10