-2
def main():
series = input('Enter series of lowercase letters:')
index = 0
vowels = 0
constants = 0
while index < len(series):
    if series[index] in "aeiou":
        vowels += 1
        index += 1
    else:
        constants += 1
index += 1
print('Vowels:', vowels)
print('Constants:', constants)
main()

好的,这样就修复了错误,但它只是为答案提供了空白空间,为什么不计算它们

4

2 回答 2

1

这里有五件事:

  1. 您需要使用方括号[...]来索引字符串。
  2. 您的 if 语句总是会返回True,因为非空字符串True在 Python 中的计算结果为。
  3. 这不是错误,但做var = var + nvar += n.
  4. 你拼错了“辅音”。:)
  5. 您需要缩进最后一个index = index + 1并删除它之前的一个。

因此,您的代码应该是这样的:

def main():
    series = input('Enter series of lowercase letters:')
    index = 0
    vowels = 0
    consonants = 0
    while index < len(series):
        # Test if series[index] is in the string "aeiou"
        if series[index] in "aeiou":
            vowels += 1
        else:
            consonants += 1
        index += 1
    print('Vowels:', vowels)
    print('Constants:', consonants)

此外,仅供将来参考,Python 正在读取您当前的 if 语句,如下所示:

if (series(index) == "a") or ("e") or ("i") or ("o") or ("u"):
于 2013-11-10T20:08:29.363 回答
1

您正在使用()而不是[]用于索引:

series(index)

其次,这也是不正确的:

if series(index) == "a" or "e" or "i" or "o" or "u":

因为它相当于:

if (series(index) == "a") or ("e") or ("i") or ("o") or ("u"):

因此,即使在使用series[index]条件之后if总是会为真,因为非空字符串("e")总是True

改用这个:

if series[index] in ("a" ,"e", "i", "o", "u"):

最后,字符串在 python 中是可迭代的,因此需要使用while循环和索引:

def main():
    series = input('Enter series of lowercase letters:')
    vowels = 0
    constants = 0
    vowels = ("a" ,"e", "i", "o", "u")
    for c in series:
        if c in vowels:
            vowels = vowels + 1
        else:
            constants = constants + 1
于 2013-11-10T20:09:03.530 回答