lundi 29 novembre 2021

Python: I'm looking to append certain numbers to a list using for loop, but I don't understand why 1 works and the other solution doesnt [duplicate]

So I'm looking to iterate through this list [1,2,4,0,0,7,5] and only append the numbers 0 and 7 to make [0, 0, 7].

So below, I included my initial attempt which didn't work.

def spy_game(mylist):
    a = []
    for i in mylist:
        if i == 0 or 7:
            a.append(i)
        else:
            pass
    print(a)

Output: [1,2,4,0,0,7,5]

Below here is the working solution, I'm not sure why the solution below works as opposed to the one above. I'm looking for a explanation for dummies kind of thing, any and all help is appreciated thanks.

def spy_game(mylist):
    a = []
    for i in mylist: 
        if i == 0:    #Removed or 7
            a.append(i)
        elif i == 7:    #added elif statement
            a.append(i)
        else:
            pass
    print(a)

Output: [0,0,7]

Aucun commentaire:

Enregistrer un commentaire