python - 为什么我的比较运算符不能在 for 循环中工作?
问题描述
我是 Python 新手,编写了一个程序来确定输入的字符串中的字母是元音还是辅音。如果字母是元音,则程序打印“元音”,但如果是辅音,则打印辅音。
我以两种不同的方式编写了程序,但无法弄清楚为什么第二个代码集不起作用。运行时,它为输入的字符串中的所有字母返回“元音”。
#this code works
word = input("Please enter a word: ")
for letter in word.lower():
if letter == 'a':
print("vowel")
elif letter == 'e':
print("vowel")
elif letter == 'i':
print("vowel")
elif letter == 'o':
print("vowel")
elif letter == 'u':
print("vowel")
else:
print(letter)
#this code doesn't work
word = input("Please enter a word: ")
for letter in word.lower():
if letter == 'a' or 'e' or 'i' or 'o' or 'u':
print("vowel")
else:
print(letter)
如果我在第一个代码集中输入“David”,它会返回 [d, vowel, v, vowel, d]。我想知道为什么第二组代码的“for”语句中的逻辑不起作用。为什么我不能在第二个代码示例中使用比较运算符“或”?当第二组代码运行时,我得到的是字符串中所有字母返回的单词“元音”
解决方案
所以你有一个困惑,在 python 中 bolean 可能会很混乱。空列表,空字符将评估为 False。非空列表和 char 将评估 True。
# when your are doing :
if letter == 'a' or 'e' or 'i' or 'o' or 'u':
您正在测试是否 letter =='a' 但如果 'e' 是非空字符。正确的形式是:
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o': # continue
在这里,您测试每种情况,第一种方式和第二种方式是等效的。
推荐阅读
- javascript - Highcharts 样条未正确定位的问题
- c# - “ArgumentException:您要实例化的对象为空” Unity,我不知道为什么
- ruby-on-rails - 确认操作后设计自定义
- sqlite - 为什么 SqliteStudio 在其 Create Table 语句中显示 DATETIME 列
- swift - 错误:EXC_BAD_ACCESS(代码=1,地址=0x6f697483)。进程已经返回到表达式求值前的状态
- opendaylight - 使用 OpenDaylight REST API 添加流时出错
- ssas - 如何使用 Oracle DW 创建 OLAP 多维数据集
- django - 使用现有键添加仅获取参数值?
- c++ - SFML Sprite 不可见
- joomla - 在扩展帮助 Joomla 中使用标签