jeudi 3 septembre 2020

Strings seperated with "OR" operator doesn't work properly with "EQUAL" (==) operator in Python3

I wanted to define a function that counts the Vowels in a string.

txt = "Celebration"

def count_vowels(string):
    count = 0
    for character in string:
        if character == "a" or "e" or "i" or "u" or "o":
            count += 1
    print(count)

count_vowels(txt)

The problem with this code is this part:

if character == "a" or "e" or "i" or "u" or "o":

Using this statement prints out "11" that means It counts every character regardless of it being vowel or not

But using these two statements work properly and prints out "5":

if character == "a" or character == "e" or character == "i" or character == "u" or character == "o":

or

if character in ["a","e","i","u","o"]:

I wonder why this happens especially the former one why do I have to write the character == "letter" statement for every character.

Aucun commentaire:

Enregistrer un commentaire