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
243 views
in Technique[技术] by (71.8m points)

Think Python (How to think like a computer scientist) - Excercise 8.4 Duckling question

I have an additional question related to the link below:

Think Python (How to think like a computer scientist) - Excercise 8.4

I tried using this method to produce a solution to the ducklings problem, but it's not producing the answer I wanted. I wish to know what is wrong with my code because I can't seem to figure it out :(

enter image description here

as you can see, I think I set the conditions right : when the letter is O or Q, you add 'u' between the prefix and suffix, and you print everything else the way it was. But the thing is, the output is adding 'u' to everything, not just O or Q.

Is there some kind of syntax error I did wrong? I'm having a hard time trying to understand what I did wrong and I would appreciate it if anyone could point out my mistake and how to fix it. Thanks.

question from:https://stackoverflow.com/questions/65913262/think-python-how-to-think-like-a-computer-scientist-excercise-8-4-duckling-q

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

1 Reply

0 votes
by (71.8m points)
if letter == 'O' or 'Q':

does not do what you think it does (see here for operator precedence), it's equivalent to:

if (letter == 'O') or ('Q'):

And, since 'Q' is a truthy value, the condition of that if statement is always true. What you would need in your case would be:

if letter == 'O' or letter == 'Q':

but a more Pythonic way would be:

if letter in ['O', 'Q']:

This also better matches your original thinking where you want to detect if the letter is any of a certain group of letters, rather than explicitly checking the letter against each and every one.


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

...