Search code examples
pythonpython-3.xfor-looptkinter

Only do this action once in a for loop


I need to do this action once under certain conditions in a for loop to stop duplicates appearing in the checkboxes. Theoretically, this should work I believe but when the conditions are met for this if statement (cycles == 1 & len(tasks) > 1) it skips over the statement anyway which really confuses me. I have been trying to debug this with breakpoints but I can't figure it out.

tasks = [a, b]

def addToList():
    cycles = 0
    for x in range(len(tasks)):
        cycles += 1
        if cycles == 1 & len(tasks) > 1:
            checkList.destroy()
        checkList = Checkbutton(viewTab,text=tasks[x])
        checkList.pack(anchor='w',side=BOTTOM)

Solution

  • The issue lies in the way you're using the '&' operator. In Python '&' is a bitwise AND operator, not a logical AND operator. For logical AND, you should use 'and'

    So, instead of:

    if cycles == 1 & len(tasks) > 1:

    You should use:

    if cycles == 1 and len(tasks) > 1: