problem with for and if

Chris Warrick kwpolska at gmail.com
Mon Jan 5 15:41:25 CET 2015


On Mon, Jan 5, 2015 at 3:27 PM, Dariusz Mysior <mysior.darek at gmail.com> wrote:
> I want search count of szukana in zmienna but code below counting all 12 letters from "traktorzysta" word

First off, I recommend that you do not write code in Polish — use
English so that everyone can understand your code.

Your error is here:
>     for a in zmienna:
>         if szukana in zmienna:

You shouldn’t be looking in `zmienna`, you should be checking `a` —
the letter of the word used in the current iteration.  Moreover, you
should use == for the comparison — compare the letter in the current
iteration to 't'.  The correct line WOULD be

    if a == szukana:

BUT there is actually a better solution.  You see, Python is a
language with “batteries included” — that is, many things are already
available for you to use without need to re-implement them.  Just use
str.count, which will do it for you:

zmienna = 'traktorzysta'
szukana = 't'
print("Literka '",szukana,"' w słowie ",zmienna,
      "wystąpiła ",zmienna.count(szukana)," razy")

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16



More information about the Python-list mailing list