I am new to python and taking an intro class, one of my homework asks to write a function that takes, as arguments, a string and a character. If the character is in the string, return the sum of the indices that the character occurs. Otherwise, return False. We can not use the find() or index() built-in functions.
This is my code so far
def addIndices(myString, myChar):
summy= 0
for i in myChar:
if i not in myString:
return False
else:
for i in myString:
if i in myString:
summy += 1
return summy
>Solution :
Here is an example code. Note you said to return the sum of indices, so you need to add the index (starting at 0) of each matching character, not just to add 1 for each matching character.
#!/usr/bin/env python
def addIndices(myString, myChar):
summy = 0
if not myChar in myString:
return False
else:
i = 0
for ch in myString:
if myChar == ch:
summy += i
i += 1
return summy
sum = addIndices('it is a test', 'i')
print(sum)