I need to write a program that does linear search on a character within a sentence. I have to do it without using any inbuilt functions except for print()
.
The program should output what index the character is at.
If the character isn't in the sentence it should output -1 as the index.
My code outputs the following:
Enter a sentence: Hello
Enter a character: e
The character is -1.
The character is 1 on the index.
Even though it should only output:
Enter a sentence: Hello
Enter a character: e
The character is 1 on the index.
Below is my code:
def linear_search(intList,target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
print("The character is", count, "on the index.")
found = True
break
if intList[count] != target:
print("The character is -1.")
count = count + 1
return count
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
Many thanks for your help!