[Tutor] Select a string
Cameron Simpson
cs at cskk.id.au
Wed Sep 6 01:49:52 EDT 2017
On 05Sep2017 22:34, Pat Martin <wpmartin at gmail.com> wrote:
>I am trying to write a program for a programming class that finds the
>number of a specific string (bob) in a string of characters. I am using one
>of the sample strings they give me and it should find 2 instances of bob
>but my script returns 0. Since they want it to find 2 from the bobob in the
>string using "bob in s" doesn't work (it only returns 1). My eyes are
>crossing looking at the code, can someone give me a hint on what I am
>missing that causes this to not give me the correct answer of 2.
>
>#!/usr/bin/env python3
>
>s = 'azcbobobegghakl'
>
>count = 0
>theo = False
>firstb = False
>
>for i in s:
> if i == 'b':
> firstb == True
This line is a boolean expression using "==", not an assignment using "=". As a
consequence firstb is never set to True and the rest of the logic never fires.
It is legal in Python to just put an expression on a line.
It is usually worth putting in print() calls to debug things like this. I put:
print(i, firstb, theo, count)
at the start of the loop and learned that firstb never becomes true. I also put
the same print statement at the bottom.
The advantage of hte above print statement is that it shows you the character
from the string along with each set of values. That way you can scan down the
output to the "bob" part and look for correct behaviour.
I that hadn't helped I've have stuck print after each "if" until the problem
became glaringly obvious.
BTW, it isn't good to write tests like:
if theo == True:
"theo" a Boolean anyway. Just say:
if theo:
It reads more naturally as well.
Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
More information about the Tutor
mailing list