【问题标题】:Python 'String Index Out of Range Error'?Python'字符串索引超出范围错误'?
【发布时间】: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


【解决方案1】:

循环中的退出条件应该是:

while position < lettercount:

或者更简单,您可以像这样遍历字符串中的每个字符:

for c in word:
    if c == 'a':
        # and so on

【讨论】:

    【解决方案2】:

    使用dictionary data structure 可能更pythonic

    vowels = { 'a' : 5, 'e' : 4, 'i' : 5, 'o' : 5, 'u' : 5}
    
    vowelscore = 0
    
    for letter in word:
        if letter in vowels:
            vowelscore += vowels[letter]
    

    【讨论】:

    • 哈哈!我写了完全相同的代码,但拒绝回答这个问题,因为我觉得它有点太自大了。另外,它没有回答 OP 提出的问题,“为什么他的代码不起作用?”。反正! :)
    • 是的。我想既然@ÓscarLópez 已经回答了 OP,我想我会建议查看他/shre 以前可能没有遇到过的数据结构:)。不过这很有趣
    • 好的,因为我们正在进入替代结构 - 如上所述定义字典,然后vowelscore = sum(vowels.get(letter, 0) for letter in word)
    • 非常感谢大家,没想到会有回复!
    猜你喜欢
    • 2015-01-19
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2019-12-24
    • 2013-09-25
    相关资源
    最近更新 更多