Okay, there’re two ways you can go about this:
If you want to have a look at how for
loops work (and following your code), you want to change a few things:
for char in s:
if count==3:
print("number of z:" + str(count))
Firstly, you need to have something which actually increments count
, otherwise it’ll remain at 0. So the first thing you should do after checking if the character is in lett
is this: count += 1
Secondly, you should only have to check count once, and that should be after the for
loop finishes (otherwise it’ll check count every time it cycles through a letter, which is a waste of memory).
Equally, your else statement should move along with it - you only want to return 0 once that for loop is finished.
Thirdly, you want to check if the count
is greater than or equal to 3, not just equal to 3. So you want if count >= 3
Finally, if you want to return 1, simply place a return 1
after your print statement.
So your code should look like this:
def punk(s):
count = 0
lett=['z']
for char in s:
if char in lett:
# increment count
if count >= 3:
# print statement followed by returning 1
else:
return 0
There is of course another way you could do this. Python has a count function for strings, for example:
myString = "Hello World"
myString.count("l")
In this case, count()
would return 3. So you could use this in place of a for
loop altogether.
Have a go and see if you can get your code working, good luck!