【发布时间】:2013-11-20 21:57:21
【问题描述】:
我今年 15 岁,目前正在攻读计算机专业的 GCSE。我的知识非常基础,我必须为“元音价值计算器”编写一段代码,该代码应该检查一个单词并根据数量和哪个给它一个元音分数它有元音。我不断收到错误,我完全被难住了,任何帮助将不胜感激。这是我的源代码:
元音值计数器
print('Welcome to the Vowel Worth Counter!')
word = input('Please input your word, in lower-case, or type Q to quit.')
if word == 'Q' :
quit()
def vowelcount(word) :
lettercount = int(len(word))
vowelscore = 0
checkcount = 1
position = 0
while lettercount != checkcount :
if word[position] == str('a') :
vowelscore = vowelscore + 5
if word[position] == str('e') :
vowelscore = vowelscore + 4
if word[position] == str('i') :
vowelscore = vowelscore + 5
if word[position] == str('o') :
vowelscore = vowelscore + 5
if word[position] == str('u') :
vowelscore = vowelscore + 5
position = position + 1
if lettercount == checkcount :
print('I have finished calculatiing your Vowel Score.')
print('Your Vowel score is ' + str(vowelscore) + '!')
for x in range (0,1) :
break
vowelcount(word)
正如我所说,任何帮助将不胜感激,谢谢。
【问题讨论】:
-
你永远不会改变
checkcount,所以你的while循环永远不会结束。 -
while lettercount != checkcount。你永远不会在你的while循环中改变任何一个,而你仍然增加position。这就是为什么你的代码快死了 -
另外,在 Python 中,直接遍历列表或字符串等数据结构比使用索引更常见。
for letter in word:将是 Pythonic 的惯用语,至少如果我不打算使用更高级的结构的话。
标签: python string indexing range