猿问

python即使条件为假也会执行if语句

这个函数的目标是计算元音,但是在所有情况下都执行 if 语句这是代码:


def count_vowels(txt):

  count=0

  txt = txt.lower()

  for char in txt:

    

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

       count = count+1

    

  print(count)


count_vowels(mark)

它必须打印 1 但它正在打印 4


达令说
浏览 111回答 1
1回答

函数式编程

问题是您将 char 与 'a' 进行比较,然后仅检查字符串值是否存在,这是一个值并且在这种情况下始终为真。def count_vowels(txt):  count=0  txt = txt.lower()  for char in txt:        if char == "a" or "e" or "i" or "o" or "u":       count = count+1      print(count)count_vowels(mark)你需要做:def count_vowels(txt):  count=0  txt = txt.lower()  for char in txt:        if char == "a" or char == "e" or char == "i" or char == "o" or char == "u":       count = count+1      print(count)count_vowels(mark)或者更清洁的选择:def count_vowels(txt):  count=0  txt = txt.lower()  for char in txt:        if char in ['a', 'e', 'i', 'o', 'u']:       count = count+1      print(count)count_vowels(mark)
随时随地看视频慕课网APP

相关分类

Python
我要回答