由于python中的“OR”操作,语法无效

时间:2013-05-28 03:07:58

标签: python

straightrunfaces = 'A23456789TJQKA';
for i in range(0,10):
        if ((counts[straightrunfaces[i]] and 
             counts[straightrunfaces[i+1]] and 
             counts[straightrunfaces[i+2]] and 
             counts[straightrunfaces[i+3]])) or
            ((counts[straightrunfaces[i+1]] and 
             counts[straightrunfaces[i+2]] and 
             counts[straightrunfaces[i+3]] and 
             counts[straightrunfaces[i+4]])):



C:\datasci_course_materials\assignment3>python poker.py
  File "poker.py", line 62
    counts[straightrunfaces[i+3]])) or
                                     ^
**SyntaxError: invalid syntax**

我不明白为什么“OR”运算符不起作用

2 个答案:

答案 0 :(得分:6)

问题不在于or,而是最后的换行符。没有打开的括号,因此换行符终止if语句;但是,if语句必须以冒号结尾,而你的语句不能以解析器结束。

添加显式的行继续:

if (counts[straightrunfaces[i]] and 
    counts[straightrunfaces[i+1]] and 
    counts[straightrunfaces[i+2]] and 
    counts[straightrunfaces[i+3]]) or \
   (counts[straightrunfaces[i+1]] and 
    counts[straightrunfaces[i+2]] and 
    counts[straightrunfaces[i+3]] and 
    counts[straightrunfaces[i+4]]):

或者用括号括起整个东西:

if ((counts[straightrunfaces[i]] and 
     counts[straightrunfaces[i+1]] and 
     counts[straightrunfaces[i+2]] and 
     counts[straightrunfaces[i+3]]) or
    (counts[straightrunfaces[i+1]] and 
     counts[straightrunfaces[i+2]] and 
     counts[straightrunfaces[i+3]] and 
     counts[straightrunfaces[i+4]])):

PEP 8推荐后者。

答案 1 :(得分:1)

尝试:

straightrunfaces = 'A23456789TJQKA';
for i in range(0,10):
    if all(counts[straightrunfaces[i]], counts[straightrunfaces[i+1]], counts[straightrunfaces[i+2]], counts[straightrunfaces[i+3]]) or all(counts[straightrunfaces[i+1]], counts[straightrunfaces[i+2]], counts[straightrunfaces[i+3]], counts[straightrunfaces[i+4]]):