使用逻辑运算符 "not" 的 While 循环说明
Explanation of While Loop Using the Logical Operator "not"
代码来自 "Think Like a Computer Scientist: 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 = True
当found = True
。
条件设置为 not found
因此循环将迭代。 (我将条件设置为 found
并且它不会迭代。因此 while 循环只能迭代 True
值)。一旦在 astring
、found = True
中找到 achar
。闭环背后的逻辑是什么?我对not
的使用有什么误解?
我认为您应该将 Not 运算符视为反相器。逻辑 table 将是:
- 一个 |不是
- T | F
- F | T
所以当 Found 为 False 时它实际上为 True,当它为 True 时它为 False。
while 循环的条件语句相当于 while True - 执行代码,while false 退出代码。
看一下条件,它是一个 and 操作,其中两个操作都必须为 True 才能为 True,如果你查找 and gate truth table 你可以了解更多相关信息。
基本上,'ix < len(astring) and not found' 都必须为真才能循环到。
希望对您有所帮助
代码来自 "Think Like a Computer Scientist: 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 = True
当found = True
。
条件设置为 not found
因此循环将迭代。 (我将条件设置为 found
并且它不会迭代。因此 while 循环只能迭代 True
值)。一旦在 astring
、found = True
中找到 achar
。闭环背后的逻辑是什么?我对not
的使用有什么误解?
我认为您应该将 Not 运算符视为反相器。逻辑 table 将是:
- 一个 |不是
- T | F
- F | T
所以当 Found 为 False 时它实际上为 True,当它为 True 时它为 False。
while 循环的条件语句相当于 while True - 执行代码,while false 退出代码。
看一下条件,它是一个 and 操作,其中两个操作都必须为 True 才能为 True,如果你查找 and gate truth table 你可以了解更多相关信息。
基本上,'ix < len(astring) and not found' 都必须为真才能循环到。
希望对您有所帮助