Mallan627
Mallan627

Reputation: 1

Python, trying to count some items in a list then stop but loop gets stuck

I got a program where you have a list and you have to count the number of words up to and including the word "sam".

import random

def sumWords(list):
    numWords = 0
    for i in list:
        if i != "sam":
            numWords += 1
    return numWords

wordList=["plant", "dog", "sam", "rose", "monkey", "happy", "coral"]    
print(sumWords(wordList))

But this counts ALL the words but Sam.

I tried doing a while i != "sam": instead of if but that puts it into an infinite loop.

Feel like I'm missing something simple here. Keep in mind though, I'm still relatively new at Python.

Upvotes: 0

Views: 1692

Answers (5)

BajajG
BajajG

Reputation: 2174

Inside the for loop, change the if statement

def sumWords(list):
    numWords = 0
    for i in list:
        numWords += 1
        if i=='sam':
            break
    return numWords

Upvotes: 0

salmanwahed
salmanwahed

Reputation: 9647

Actually you do not need a function for this. Find the index of the word and add 1 with it to include that word.

 wordList.index('sam') + 1

Upvotes: 1

dragon2fly
dragon2fly

Reputation: 2419

Your code doesn't stop counting at sam but skipping it. You should reverse the if clause and break.

def sumWords(my_list):
    numWords = 0
    for i in my_list:
        numWords += 1
        if i == "sam":
            break
    return numWords

And, you can simplify your function by:

def sumWords_simple(my_list):
    return my_list.index('sam')+1

index return the first index of the first sam in the list. Python is zero-based index. Without +1, it will be the sum up to but not including sam. With +1, it will include the fisrt sam.

Upvotes: 0

masteryoom
masteryoom

Reputation: 81

Your for loop doesn't break, so you just keep counting the words until the end of the list. What you should do is break out of the loop when you reach something equal to "sam", which you simply need to rewrite your code to this:

for i in list1:
    numwords += 1
    if i == "sam":
        break

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

You can use simple break statement when i =="sam". It will ensure you loop will only iterate until sam, rather than the whole list.

def sumWords(list):
    numWords = 0
    for i in list:
        numWords += 1 # Increment in each iteration.
        if i == "sam": # if condition matches, break from the loop
            break 
    return numWords

Usage:

print sumWords(wordList)

Output:

3

Upvotes: 1

Related Questions