Jason HJH. Jason HJH. - 3 months ago 18
Python Question

Python For Loop from How to think like a computer scientist

I stumbled upon a new exercise in "How to Think like a Computer Scientist". (Open documentation @ http://www.openbookproject.net/thinkcs/python/english2e/ch07.html)

Hope to receive some directions on this:

prefix="JKLMNOPQ"
suffix="ack"

for letter in prefix:
print letter + suffix


and you get
Jack, Kack, Lack, Mack, Nack, Oack, Pack & Qack.

What should I modify so that instead of Oack and Qack, I get Ouack and Quack?

For the sake of learning, what I attempted was:

prefix="JKLMNOPQ"
suffix="ack"

for letter in prefix:
if letter = "O" or "U":
print letter + "u" + suffix
else:
print letter + suffix


As most of you would notice at first sight, the syntax error committed is in using = instead of == in the if function call.

Thanks for all your prompt assistance, I greatly appreciate them.

Answer

The given example relies on the fact that when iterated, a string gives each of its individual characters. Since you want some of your prefixes to have two characters, you have to break up your string into a separate one for each of the characters and add the u where you want it.

prefixes=["J", "K", "L", "M", "N", "Ou", "P", "Qu"]
suffix="ack"

for letters in prefixes:
    print letters + suffix
Comments