首页 > 解决方案 > 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

标签: pythonpython-3.x

解决方案


问题是您将 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)

推荐阅读