problem with for and if

MRAB python at mrabarnett.plus.com
Mon Jan 5 09:48:53 EST 2015


On 2015-01-05 14:27, Dariusz Mysior wrote:
> I want search count of szukana in zmienna but code below counting all 12 letters from "traktorzysta" word
>
> szukana="t"
> zmienna="traktorzysta"
>
>
> def gen():
>      count=int(0)
>      for a in zmienna:
>          if szukana in zmienna:
>              count+=1
>          else:
>              continue
>      return count
>
>
> print("Literka '",szukana,"' w słowie ",zmienna,
>        "wystąpiła ",gen()," razy")
>
It's asking whether szukana is in zmienna for each character in zmienna.

There are 12 characters in zmienna, so it's asking 12 times.

Because szukana is in zmienna, it adds 1 to count each time, giving a
total of 12.

If szukana wasn't in zmienna, then nothing would be added to count,
giving a total of 0.

The body of the loop should be:

       for a in zmienna:
           if a == szukana:
               count += 1

Other notes:

0 is already an int, so int(0) is just 0!

There's no need for the 'else' part in the 'if' statement

Strings have a .count method, so you can, in fact, simplify it to just:

def gen():
     return zmienna.count(szukana)




More information about the Python-list mailing list