Home > Blockchain >  Increment index in for loop only if condition met
Increment index in for loop only if condition met

Time:09-04

I'm currently learning Python and run into a bit of a snag. I'm building a simple to-do list, and I've built it out to display a list only if the first character is a ❌. This works, but when an item is marked complete (with a ✅), it still counts increments the index on the code below.

I assumed that index = 1 inside an if statement would only increment the index if the condition is met - is this not the case?

def read_list():
read_list = open("todo.txt","r", encoding='utf-8')
for index, item in enumerate(read_list, 1):
    item = item.rstrip('\n')
    if item[0] == '❌':
        print(f'{index}. {item}')
        index  = 1

The current output of this is:

1. ❌ TASK 1
3. ❌ TASK 2

This is because the second item on the list is '✅ TASK 3'

CodePudding user response:

for index, item in ... already increments index. On your first loop, you are printing (current index 1) then adding (current index 1) 1 which is 2 then increments 1 with for loop. So in your second loop, it prints 3.

Create a separate variable outside of the for loop:

numTasksIncomplete = 0
for index, item in enumerate(read_list, 1):
    item = item.rstrip('\n')
    if item[0] == '❌':
        print(f'{index}. {item}')
        numTasksIncomplete  = 1

CodePudding user response:

You need to understand the purpose of variable index you are trying to increment.

Currently, index and item and assigned new values everytime the loop iterates over read_list. index and task in the for loop with enumerate basically resolves to getting the index and value from read_list one by one.

You are trying to increase the same variable index inside if condition. Even if you increament it, next time the loop runs, it will overwrite the value.

If you are trying to count the number of tasks that are incomplete, you can use a new variable and name it different that one you are using in the for loop.

Try this :

incomplete_count = 0
for index, item in enumerate(read_list, 1):
    item = item.rstrip('\n')
    if item[0] == '❌':
        print(f'{index}. {item}')
        incomplete_count  = 1
  • Related