Python语句总是被执行帮助

时间:2013-05-02 23:22:58

标签: if-statement python-3.x logic

我有以下条件声明:

if (sc == 'Both') and (fc == 'True') or (bc == 'True'):
     do this
if (sc == 'Front') and (fc == 'True'):
     do this
if (sc == 'Back') and (bc == 'True'):
    do this

问题是第二个和第三个子句按预期工作,但是,如果sc等于fc和bc都为假,则该语句仍然执行,我不知道原因。

1 个答案:

答案 0 :(得分:1)

你写了

if ((sc == 'Both') and (fc == 'True')) or (bc == 'True'):
     do this
if (sc == 'Front') and (fc == 'True'):
     do this
if (sc == 'Back') and (bc == 'True'):
    do this

我认为你的意思是

#                                     or binds weaker than and so it needs brackets
if (sc == 'Both') and ((fc == 'True') or (bc == 'True')):
     do this
if (sc == 'Front') and (fc == 'True'):
     do this
if (sc == 'Back') and (bc == 'True'):
    do this

您可以andor对数字的任何操作都较弱,所以这也是正确的:

if sc == 'Both' and (fc == 'True' or bc == 'True'):
     do this
if sc == 'Front' and fc == 'True':
     do this
if sc == 'Back' and bc == 'True':
    do this