这个函数的目标是计算元音,但是在所有情况下都执行 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 回答
函数式编程
TA贡献1807条经验 获得超9个赞
问题是您将 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)
添加回答
举报
0/150
提交
取消