python - 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
解决方案
问题是您将 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)
推荐阅读
- python - 我的更改昵称命令突然不起作用
- c# - 编辑:NGINX 反向代理 ASP.NET Core 5.0:localhost:5000 关闭连接但 www.google.com 有效
- tensorflow - 我收到“来自未知节点的请求张量连接:“keras_layer_input:0””。加载keras模型时出错
- ionic-framework - Ionic appflow 实时更新不会出现在设备上
- javascript - 从 php 返回一个可迭代对象到 Ajax
- javascript - “text/html - npm http-server”的非 JavaScript MIME 类型
- c# - 从 .doc 格式的 word 文档的 base64String 转换为 png(mime application/octet-stream)
- loops - 为什么我的 for 循环 (i) 停止了 50,000 左右?
- lua - 重复直到循环后如何设置变量?
- javascript - 如何通过更改全局变量来更改 SurveyJS JSON 中的变量