由于某种原因,如果没有else语句,代码将查找字符串中字符的索引。但是,当我添加else语句来声明是否找不到字符时。它所做的就是给我else语句,即使字符在字符串中。If else用于查找字符串中字符索引的语句
#Function takes a character and a string and returns the index of the character
#found in the string.
def whereIsItS(letter, word):
#Start finding the index of characters in the string starting at 0.
letInWord = 0
#For loop to find specific characters in a string.
for l in word:
#If the letter is found it returns the index of the letter.
if l == letter:
#Moves to the next character in the string.
letInWord += 1
else:
return "It is not there."
#Returns the index of the character found the string.
return word.index(letter)
我似乎无法弄清楚为什么它没有else语句,但没有else语句。
因为如果该单词的第一个字母不是所需的字母;它立即返回。你可以做更好的计算索引。我想你想避免'index'返回的异常。 –
你的函数有11行代码(我计算!),这些代码是毫无意义的,然后它返回内建'index'方法的结果。为什么? – zvone
我仍然处于编程初期,并且认为我必须通过字符串中的字符来计算for循环以获取索引。我仅在2周前开始>< – Wiggs