【发布时间】:2018-08-17 22:06:10
【问题描述】:
来自“像计算机科学家一样思考:Python”的代码
def find(astring, achar):
ix = 0
found = False
while ix < len(astring) and not found:
if astring[ix] == achar:
found = True
else:
ix = ix + 1
if found:
return ix
else:
return -1
我已经通过 CodeLens 在 not 的所有位置变化和 found 的原始值中运行了这个,但我无法理解 Python 以这种形式处理其条件的方式。请指出我的思路哪里出了问题或者我错过了什么:
如果found = False,那么not found = Truefound = True。
条件设置为not found,因此循环将进行迭代。 (我将条件设置为 found 并且它不会迭代。所以 while 循环只能迭代 True 值)。一旦在astring、found = True 中找到achar。这个闭环背后的逻辑是什么?我对not的使用有什么误解?
【问题讨论】:
-
“如果找到 = False,则未找到 = True 当找到 = True” - 到底是什么?
-
一旦在
astring中找到achar,您就想停止查找,从而停止循环,不是吗?所以你设置found = True以结束循环。你问的是这个吗? -
致用户:我的逻辑哪里错了?将变量设置为 True 或 False。然后在其上使用 not 运算符。不是在检查条件时使用 not 运算符,但您想要相反吗?
-
jwodder,是的,这就是我要问的。但具体来说,我要问
found = True时停止的逻辑是什么,因为对我来说,not found = True,那么条件的变化发生在哪里?我对not运算符缺少什么? -
@Tyler_P:我相信 user2357112 对您写的“如果找到 = False ... 当找到 = True”这一事实作出反应,这是没有意义的。
标签: python python-3.x while-loop logical-operators