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()
好的,以便修复错误,但它只是为答案提供了空白,为什么不计算它们
答案 0 :(得分:1)
这里有五件事:
[...]
来索引字符串。True
,因为非空字符串在Python中评估为True
。var = var + n
与var += n
相同。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"):
答案 1 :(得分: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
条件始终为True,因为非空字符串("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