【发布时间】:2017-04-15 03:31:32
【问题描述】:
当我尝试执行此代码时,我不断收到“IndexError: string index out of range”错误消息:
#function countLetters(word,letter) should count the number of times
#a particular letter appears in a word.
def countLetters(word, letter):
count=0
wordlen=len(word)
num=0
wordletter=""
while(num<=wordlen):
wordletter=word[num]
if(wordletter==letter):
count=count+1
num=num+1
return count
print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1
错误信息:
Traceback (most recent call last):
File "C:\Users\Charlie Chiang\Desktop\9G.py", line 17, in <module>
print(countLetters("banana", "x"))
File "C:\Users\Charlie Chiang\Desktop\9G.py", line 10, in countLetters
var=word[num]
IndexError: string index out of range
【问题讨论】:
-
在我看来,正在运行的代码和您正在查看的代码是不同的。您的来源中没有
var=word[num],而Traceback似乎认为有 -
@shaktimaan:已经够近了;而不是
var,而是wordletter=word[num]。 -
仅供参考,我不知道这是否用于分配,但您始终可以使用
.count()。示例:"banana".count("a")返回3。 -
是的,我正在上课,这是一项作业。