使用 if/else 制作初学者系列的语义错误
我的程序应该输出: Jack、Kack、Lack、Mack、Nack、Ouack、Pack 和 Quack。
suffix="ack"
prefix="JKLMNOPQ"
for i in prefix:
if prefix=="Q" or "O":
suffix="uack"
else:
suffix="ack"
print i + suffix
但它却输出 尤克、库克、卢克、穆克·努克 瓦克 普阿克 嘎嘎
My program is supposed to output:
Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack.
suffix="ack"
prefix="JKLMNOPQ"
for i in prefix:
if prefix=="Q" or "O":
suffix="uack"
else:
suffix="ack"
print i + suffix
But instead it outputs
Juack, Kuack, Luack, Muack Nuack
Ouack
Puack
Quack
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
前缀
(包含多个字母的字符串)(而不是当前字符i
)与单个字母进行比较。他们永远不平等。我建议使用更好的名称(这会使错误变得明显):prefixes = "JK..."
和for prefix in prefixes:
。"O"
将其强制转换为布尔值,而不使用任何比较运算符。如果prefix=="Q"
为 false,则会将"O"
转换为布尔值 - 并且非空字符串被视为 true。使用prefix == "Q" 或 prefix == "O"
或prefix in ("Q", "O")
(这样可以更好地扩展更多选择)。你不会相信这个错误有多常见......是的,它恰好使用了一些从英语借用的关键字,但它不是英语;prefix
(a string containing several letters) - instead of the current character,i
- to single letters. They are never equal. I'd suggest better names (which would make the error obvious):prefixes = "JK..."
andfor prefix in prefixes:
."O"
to a boolean by using it, without any comparision operator, in a logical or. Ifprefix=="Q"
is false, it converts"O"
to a boolean - and non-empty strings are considered true. Either useprefix == "Q" or prefix == "O"
orprefix in ("Q", "O")
(which scales better for more alternatives). You wouldn't believe how common this error is... yeah, it happens to use a few keywords borrowed from english, but it's not english </rant>prefix == "Q" 或 "O"
是完全错误的。"JKLMNOPQ"
,因此永远不会等于"Q"
。我认为您的意思是检查i
而不是prefix
==
绑定比or
更近,因此它将评估到(前缀==“Q”)或“O”
。“O”
始终为真,因此后缀始终为“uack”`如果您修复了这些问题,它应该可以工作。
我认为应该是
if i=="Q" or i=="O"
。prefix == "Q" or "O"
is completely wrong."JKLMNOPQ"
and so will never be equal to"Q"
. I think you meant to check fori
rather thanprefix
==
binds closer thanor
so it will evaluate to(prefix == "Q") or "O"
."O"
is always true so suffix will alwasy be "uack"`If you fix these, it should work.
I think it should be
if i=="Q" or i=="O"
.您应该在循环中与
i
而不是prefix
进行比较。即使您自'O 以来与
不是i
进行比较,if prefix == 'Q' or 'O'
也始终为True
'False
。这应该是如果 i == 'Q' 或 i == 'O'
。You should be comparing against
i
instead ofprefix
in the loop. Theif prefix == 'Q' or 'O'
would always beTrue
even if you were comparing againsti
since'O'
is notFalse
. This should beif i == 'Q' or i == 'O'
.