2016-01-16 63 views
1

当我运行这段代码时,什么也没有显示出来。例如,我打电话给ind(1, [1, 2, 3]),但我没有得到整数13Python中的运算符不起作用

def ind(e, L): 
    if (e in L == True): 
     print('13') 
    else: 
     print('12') 
+0

实际上你应该会收到一个错误。在Python中,它是“真”,而不是“真”。 – thefourtheye

+0

'L'就足够了 –

+0

'如果L:'中的e就够了。 –

回答

4

运算符优先级。如果你把()周围e in L它会工作:

def ind(e, L): 
    if ((e in L) == True): 
     print('13') 
    else: 
     print('12') 

ind(1, [1, 2, 3]) 

但测试的True可以做到的(并且是通常的成语),而不True

def ind(e, L): 
    if (e in L): 
     print('13') 
    else: 
     print('12') 

ind(1, [1, 2, 3]) 

编辑完成的:作为奖励你甚至可以使用TrueFalse来保持/取消操作。随着你的榜样:

def ind(e, L): 
    print('13' * (e in L) or '12') 

ind(1, [1, 2, 3]) 

ind(4, [1, 2, 3]) 

这。OUPUTS:

13 
12 

因为e in L已首先评估,以True13 * True13。不查找布尔表达式的第二部分。

但随着4调用函数时,则将发生以下情况:

`13` * (e in L) or '12` -> `13` * False or '12' -> '' or '12' -> 12 

becase的和空字符串的计算结果为False太多,因此返回or布尔表达式的第二部分。

+0

尽管在这里可以使用''13'*(e,L)或'12',但对于不支持“*”的操作数起作用的更一般的解决方案是'在L和'13'或'12'中。或者,使用一个条件表达式使其更具可读性:“'13''如果在L'else'12'中。另一种选择是'('12','13')[尽管L'],尽管这可能是选项中最不可读的。 –

0

应该

def ind(e, L): 
    if (e in L): 
     print ('13') 
    else: 
     print ('12') 

这里IND(1,[1,2,3])将打印13

这是我的证明,上面的语法在我的机器上运行:

enter image description here

+2

我建议你测试一下。 – TigerhawkT3

+0

1)您不能将Python关键字'in'用作函数名称(或任何其他名称)。 2)你不需要围绕'if'条件的括号,并且忽略它们是正常的Python风格。 –

+0

@ TigerhawkT3我在回答问题之前运行了整个事情。 –