Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having trouble with an if statement with an or statement embedded in a for loop

random_characters = "adak"

for letter in random_characters:
    print(letter)
    if letter == "a":
        print("Vowel")

…emits as output:

a
Vowel
d
a
Vowel
k

If I only include one letter in the if statement the code runs fine. However, If I add one more through an or statement…

a
Vowel
d
Vowel
a
Vowel
k
Vowel

"Vowel" is printed after every iteration.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m going to read between the lines and guess that you have made the very common mistake of writing:

    if letter == "a" or "e":

because that would produce the results you see. The reason is, that is interpreted as

    if (letter == "a")  or  "e":

and since "e" is always True, the if is always taken. If you want to compare to multiple letters, use in:

    if letter in ("a","e","i","o","u"):

although in this case, you could also write:

    if letter in "aeiuo":
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading