Skip to content Skip to sidebar Skip to footer

Showing And Returning The Number Of A Repeated String On A Function?

I'm already learning Python on a online free course. Now I have and exercise that I've been hours trying to do but.... I cannot see why it doesn't works.. The instructions are here

Solution 1:

To fix your specific issue:

x=["fizz","bear","fizz"]

deffizz_count(x):
    count= 0for e in x:
        if e=='fizz':
            count = count + 1return count

print fizz_count(x)

A few issues:

  1. No need of *x in the parameter in python
  2. Use a different variable name when you are iterating through the elements.
  3. count=0 is sufficient, no need to cast it as a string
  4. if x=='fizz' should be if e=='fizz' - Check the element of the list, rather than the entire list.
  5. The return statement had to be after the loop executes. Notice the indentation.

Ofcourse, there are better ways of achieving what you are looking for, but I shall leave it here as it seems like you are learning.

Hope this helps.

Solution 2:

Few things about your script:

deffizz_count(*x)

This probably isn't the syntax you want here. What you're doing here is expanding the list so it takes its own argument slot. You probably want to pass it like this:

deffizz_count(x)

Next:

count = str(0)

You can simply initiate your counter like this:

count = 0

Next:

forcountin x:

This now makes your count variable an entry in x, but since you expanded the list this probably isn't what you're seeing. Regardless, again, you want something like this to assign each member to a variable:

foritemin x:

Next:

count=count+str(1)

Again, you don't need to convert this to a string, count=count+1 would suffice

Finally, not sure if it's just a formatting issue, but your return statement should be outside your for-loop.

Post a Comment for "Showing And Returning The Number Of A Repeated String On A Function?"