samedi 24 juin 2017

Python If/Elif/Else, For and Lists

I'm trying to iterate elif statements over lists with an else statement at the end. Here is my code:

    if clickPoint is None:
        print(clickPoint)
    for each in meal_objects:
        if inside(clickPoint, each._button):
            each._button.setFill('green')
            break
    for each in build_meal_objects:
        if inside(clickPoint, each._button):
            each._button.setFill('green')
            break
    for each in ingredient_objects:
        if inside(clickPoint, each._button):
            each._button.setFill('green')
            break
    else:
        print(clickPoint)

meal_objects, build_meal_objects, and ingredient_objects are lists.

The problem is that this code is horrible for many reasons. If the first condition is not met, each for loop will be run even if one of the for loops conditions is already ran, and the final else statement will also be ran. Really, if any of the if statements within any of the for loops is met, then the rest of the if block should not execute.

The code should really be something more like this pseudocode:

    if clickPoint is None:
        print(clickPoint)
    elif for each in meal_objects:
        if inside(clickPoint, each._button):
            each._button.setFill('green')
            break
    elif for each in build_meal_objects:
        if inside(clickPoint, each._button):
            each._button.setFill('green')
            break
    elif for each in ingredient_objects:
        if inside(clickPoint, each._button):
            each._button.setFill('green')
            break
    else:
        print(clickPoint)

I feel like I might be overlooking something really simple, so forgive me if that is the case or if this is a poorly written question. Thanks!

Aucun commentaire:

Enregistrer un commentaire