首页 > 解决方案 > 为什么我的比较运算符不能在 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

解决方案


所以你有一个困惑,在 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

在这里,您测试每种情况,第一种方式和第二种方式是等效的。


推荐阅读