problem with for and if
YBM
ybmess at nooos.fr.invalid
Mon Jan 5 09:39:57 EST 2015
Le 05/01/2015 15:27, Dariusz Mysior a écrit :
> 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")
In the for loop a is iterating through "traktorzysta" ("t", then "r",
then "a", ...): 12 steps
moreover the expression szukana in zmienna is always true (as t is
a letter of "traktorzysta"), so count += 1 is executed twelve times.
def gen():
count=int(0)
for a in zmienna:
if a == szukana:
count+=1
else:
continue
return count
will work (even if quite ugly, why int(0)? why defining a function
without parameters? etc.)
More information about the Python-list
mailing list