vendredi 4 juin 2021

"If" and "Else" statements happening in the same "for" statement - Python

I am somewhat new to Python so excuse me if this is an obvious mistake but after looking at many resources I cannot find a solution. What I want to happen is the code asks for 10 different letters (or any string technically), and if the letter typed isn't already in the array I.E. hasn't been typed before, it gets added to the array. The next time you type that same letter, it wouldn't add it to the array since that same letter is already in that array. this is my code:

ArrayLetter = ["INITIAL"]

for i in range(10):
    Letter = input("Letter: ")
    for i in range(len(ArrayLetter)):
        if ArrayLetter[i] == Letter:
            print("Letter already listed!")
        else:
            print("Not listed, adding letter to list!")
            ArrayLetter.append(Letter)
            break

This is a shortened output I get when testing this script:

Letter: A
Not listed, adding letter to list!
Letter: B
Not listed, adding letter to list!
Letter: A
Not listed, adding letter to list!

I hope this isn't too much of an obvious answer but as you can see, even though "A" is inputted twice, but keeps appending it to the array.

Thanks!

Aucun commentaire:

Enregistrer un commentaire