1
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**

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

4

2 回答 2

7

问题不在于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推荐后者。

于 2013-05-28T03:13:00.713 回答
0

尝试:

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]]):
于 2013-05-28T03:13:22.477 回答