Python 3测试顺序未确定 string='a' p=0 而(p

Python 3测试顺序未确定 string='a' p=0 而(p,python,comparison,python-3.x,boolean,Python,Comparison,Python 3.x,Boolean,您没有使用正确的布尔值和。使用它,您就不会看到这个问题。您使用的(&)是一个按位比较,它会对两边进行计算。您需要使用and和or而不是按位运算符&and按位和“a&b”,应该被认为是 string='a' p=0 while (p <len(string)) & (string[p]!='c') : p +=1 print ('the end but the process already died ') while (p

您没有使用正确的布尔值
。使用它,您就不会看到这个问题。您使用的(
&
)是一个按位比较,它会对两边进行计算。

您需要使用and和or而不是按位运算符&and

按位和“a&b”,应该被认为是

string='a'
p=0
while (p <len(string)) & (string[p]!='c') :
                    p +=1

print ('the end but the  process  already died ')
       while (p <1) & (string[p]!='c') :
IndexError: string index out of range
a:   ...  0 1 1 0
b:   ...  1 0 1 0
         --------
a&b  ...  0 0 1 0   <- each bit is 1 if-and-only-if the
                       corresponding input bits are both 1
因此,从图形上看

function _bitwise_and(A,B):
    # A and B are Python expressions
    #   which result in lists of 1's and 0's

    a = A.evaluate()
    b = B.evaluate()

    return [ 1 if abit==1 and bbit==1 else 0 for abit,bbit in zip(a,b)]

注意:如果A的结果是falsy,则B永远不会被计算-因此,如果表达式B在计算时有错误,按位并将导致错误,而逻辑并不会

这是常见Python习语的基础

function _and(A,B):
    # A and B are Python expressions which result in values having truthiness

    a = A.evaluate()
    if is_truthy(a):
        b = B.evaluate()
        return b
    else:
        return a
…因为只有当偏移量是可用(不产生错误)值时,才会计算数据[offset]

通过使用“&”而不是“and”,可以通过在循环结束时计算数据[last_offset+1]来保证错误

当然,这本可以用另一个常见的成语来避免:

while (offset in data) and test(data[offset]):
    do_something_to(data[offset])
    next offset

这就完全避免了索引器的问题。

为什么要使用逐位
&
运算符?这不是一种重新设计代码的方法。那么
p=string.find(c)
(如果不存在,则返回-1而不是
len(string)-1
,这样更好,就像在中一样,不含糊不清)?
for ch in string if ch=='c':
    do_something_to(ch)