Detecting how many strings are present in a given variable?
<p>I'm trying to make a function that when you input a table, for example 'Fish, Carrot, Beef, Fish' it detects how many times 'Fish' was inputted, in this case 2. But when I try to do this it returns 'None' instead of 2.</p>

<pre><code>def word_count(x):
    count = 0
    for item in x:
        if item == 'Fish':
            count = count + 1
            return count
word_count(['Fish', 'Carrot', 'Beef', 'Fish'])
</code></pre>

<p>Any help would be appreciated as I'm quite new to Python, thank you.</p>

<p><strong>Issue with your code</strong>: Your function is <code>return</code>ing value within the <code>if</code> statement. So, when there is no <code>Fish</code> in your <code>x</code> list, it will return <code>None</code> (<em>which is default value returned by a function in Python</em>). Try below code and it will work:</p>

<pre><code>def word_count(x):
    count = 0
    for item in x:
        if item == 'Fish':
            count = count + 1
    return count 
</code></pre>

<p><strong>Suggestion</strong>: You may simplify you function by using the <code>count()</code> function present with lists. For example:</p>

<pre><code>&gt;&gt;&gt; my_list = ['Fish', 'Carrot', 'Beef', 'Fish']
&gt;&gt;&gt; my_list.count('Fish')
2
</code></pre>

python