-2
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.

  • 3
    please edit the question and show the failing example – OldProgrammer Apr 04 '22 at 22:10
  • Note that we're a Q&A database, not a message forum. Please try to write your question like what you'd see as a FAQ entry, instead of as a conversation. – Charles Duffy Apr 04 '22 at 22:11
  • 4
    That said, you really need to show us the code that _fails_, not the code that works. I assume you're writing `letter == "a" or "e"`, and that's a clear problem, but we shouldn't have to assume. – Charles Duffy Apr 04 '22 at 22:12
  • Please update your question title. There is nothing in the current title that summarizes the problem. – paddy Apr 04 '22 at 22:12
  • It'd also be useful to know what you change to make the code fail, since that's the crux of the issue. – Steve Butler Apr 04 '22 at 22:13
  • I didn't expect such fast results but ok I'll try to meet your requests. – quagmireizzy Apr 04 '22 at 22:14
  • Your best bet for an updated Python test on whether a particular character is one of a set of qualifying characters is something like `if letter in "aeiou":` – Joffan Apr 04 '22 at 22:14
  • BTW, you can put downvotes and close votes on hold by temporarily deleting your question, and then undeleting it when you're done editing. (At least, you can do that _before it's answered_; when @timroberts added an answer to the question, he also may have limited your ability as a low-rep user to unilaterally delete). – Charles Duffy Apr 04 '22 at 22:17
  • Thanks Joffan thats a way more condensed way of doing what I did fantastic. – quagmireizzy Apr 04 '22 at 22:17

1 Answers1

1

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":
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30