Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - "if" loop nested into a "for" loop does not work as expected

Long story short I have this exercise to complete:

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 tries to output these names in order.

Of course, that’s not quite right because Ouack and Quack are misspelled. Can you fix it?

The code that I've been given:

prefixes = "JKLMNOPQ"
suffix = "ack"

for p in prefixes:
    print(p + suffix)

After different try I managed to solve it like that:

prefixes = "JKLMNOPQ"
suffix = "ack"

for p in prefixes:
    if p=="O" or p=="Q":
        print(p + "u" + suffix)        
    else:            
         print(p + suffix)

It looks a little bit too much "hardcode" to me. Do you think it is a valid solution ?

Then I tried, just for the sake of comprehension, to do something similar by myself. So I wrote the following code:

list=["ABCD"]
for l in list:
    if l =="A" or l=="B":
        print("ok")
    else:
        print(l)

Basically I want it to print "ok" when L is equal to A or B and L (so "C" and "D") otherwise. But instead the output is:

ABCD

If I delete the last print command, no output is printed. What's wrong ? It looks pretty similar to the one I solved but still it doesn't work as I expect. What am I missing ? Thank you guys, and happy new year.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your first code, prefixes = "JKLMNOPQ" is one string, so when iterating on it, you iterate over its char. But then with list=["ABCD"] its a list of ONE element, so when iterating on it you have only one element who is ABCD

values = "ABCD"
for l in values:
    if l in "AB":
        print("ok")
    else:
        print(l)

Also if p=="O" or p=="Q" can be replaced by if p in "PQ". you can also put the if directly inside the print call

prefixes = "JKLMNOPQ"
suffix = "ack"
for p in prefixes:
    print(p + ("u" if p in "PQ" else "") + suffix)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...