# [Tutor] New to programming question

Brian van den Broek bvande at po-box.mcgill.ca
Tue Apr 12 19:30:39 CEST 2005

```Ben Markwell said unto the world upon 2005-04-12 12:56:
> This is an exercise from "How to think like a Computer Scientist."
>
>
> The following example shows how to use concatenation and a for loop to
> generate an abecedarian series. "Abecedarian" refers to a series or list in
> which the elements appear in alphabetical order. For example, in Robert
> McCloskey's book *Make Way for Ducklings*, the names of the ducklings are
> Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs
> these names in order:
>
> prefixes = "JKLMNOPQ"
> suffix = "ack"
>
> for letter in prefixes:
> print letter + suffix
>
> The output of this program is:
>
> Jack
> Kack
> Lack
> Mack
> Nack
> Oack
> Pack
> Qack
>
> Of course, that's not quite right because "Ouack" and "Quack" are
> misspelled.*
> *
>
> *As an exercise, modify the program to fix this error.
> *
>
> ==================================================
>
> In trying to solve the problem I have come up with the following:
>
> prefixes = 'JKLMNOPQ'
> suffix = 'ack'
> xsuffix = 'uack'
>
>
> for letter in prefixes:
> n = 0
> if prefixes[n] == 'O' or 'Q':
> print prefixes[n] + xsuffix
> else:
> print letter + suffix
>
> --- I know it doesn't work, but want to know if I am on the right track. And
> what is the solution?
>
> Thanks
>
> Ben
> **
>

Hi Ben,

in generally, it is a good idea to say *why* it doesn't work.
Sometimes it won't be clear what you expected as output, so it also
won't be clear why you are disappointed.

That said, see if this helps:

>>> if 'Q' == 'O' or 'Q': print "Yep (or is it?)"
...
Yep (or is it?)
>>> if 'B' == 'O' or 'Q': print "Yep (or is it?)"
...
Yep (or is it?)

Probably not what is wanted. What happens here is Python first evaluates
'Q' == 'O'
and, if it evaluates to true, returns it. But, in neither case does it
evaluate to true. So Python then turns to evaluating 'Q'. But that
*always* evaluates to true. So Python returns 'Q', and the if test
above is always met. See:

>>> if 'Q': print "That evaluated to True"
...
That evaluated to True
>>> False or 'Q'
'Q'
>>> 42==42 or 'Q'
True
>>> 42==17 or 'Q'
'Q'
>>>

There are a couple of different ways to get the test I think you want.
Here's what I'd do:

>>> if 'Q' in ('O', 'Q'): print "Thank goodness!"
...
Thank goodness!
>>> if 'B' in ('O', 'Q'): print "Thank goodness!"
...
>>>

Now, fix that up so it is not testing a hardcoded value (i.e. make it
other than "if 'Q' ... ") and see if that helps.

Post again if not.

Best,

Brian vdB

```