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

时间:2020-07-24 18:53:32

标签: python python-3.x

此函数的目标是计算元音,但是在所有情况下都将执行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

1 个答案:

答案 0 :(得分: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)