Reputation: 69
I am just learning Python and I want to check if a list contains a word. When I check for the word it always returns 0, even though the function can find it and print it. But the if/else statement always return 0, when I use 2 returns as below. Can you help me?
def line_number(text, word):
"""
Returns the line number (beginning with 1) where the word appears for the first time
:param text: Text in which the word is searched for
:param word: A word to search for
:return: List of Line Numbers
"""
lines = text.splitlines()
i = 0
for line in lines:
i = i +1
if word in line:
return i
else:
return 0
# print("nope")
words = ['erwachet', 'Brust', 'Wie', 'Ozean', 'Knabe']
for word in words:
num = line_number(wilhelm_tell, word)
if num > 0:
print(f"Das Word {word} findet sich auf Zeile {num}.")
else:
print(f"Das Wort {word} wurde nicht gefunden!")
Upvotes: 1
Views: 76
Reputation: 510
I think the problem might be that you are returning 0 if the word is not within a line. When you use the return keyword, it will exit the function and return the value. So if a word is not within the first line of the text, it will return 0 (even though the word is present on further lines)
Here is a little example of what i think is happening:
def is_element_within_list(element_to_search, some_list):
for element in some_list:
if element == element_to_search:
return True
else:
return False
some_list = [1, 2, 3]
element_to_search = 2
print(is_element_within_list(element_to_search, some_list))
# output: False
We have a function that checks if an element is within a list (we could use the keyword "in", but is for the sake of the example). So, despite that 2
is within some_list
, the function output is False
, because the function is returning False
on the else if the elements are no the same
Upvotes: 1
Reputation: 300
You should return 0
after the for loop ends and not inside the loop.
def line_number(text, word):
"""
Returns the line number (beginning with 1) where the word appears for the first time
:param text: Text in which the word is searched for
:param word: A word to search for
:return: List of Line Numbers
"""
lines = text.splitlines()
i = 0
for line in lines:
i = i +1
if word in line:
return i
return 0
The problem is the else
statement inside the loop because it will break the loop in the first iteration.
Upvotes: 2
Reputation: 46
I think the problem is that you're returning 0 on the first line the word is not in. So instead, you should return 0 after you looked through every line:
def line_number(text, word):
"""
Returns the line number (beginning with 1) where the word appears for the first time
:param text: Text in which the word is searched for
:param word: A word to search for
:return: List of Line Numbers
"""
lines = text.splitlines()
i = 0
for line in lines:
i = i +1
if word in line:
return i
return 0
Upvotes: 2