更新时间:2023-11-13 16:13:22
运算符优先级。如果您在L
附近放置(
和)
,将工作:但是可以完成 True
的测试通常成语)没有真正
def ind(e,L ):
if(e in L):
print('13')
else:
print('12')
ind(1 ,[1,2,3])
编辑:作为奖励,您甚至可以使用 True
和 False
来保留/取消操作。用你的例子:
def ind(e,L):
print('13'*(e in L ),或'12')
ind(1,[1,2,3])
ind(4,[1,2,3])
这个输出:
13
12
因为 True $ c>并且
13 * True $ c>是
13
。不查找布尔表达式的第二部分。
但是当用 4
调用函数时,则发生以下情况:
`13` *(e in L)or '12` - > `13` *假或'12' - > ''或'12' - > 12
空字符串计算结果为 False
因此返回或
布尔表达式的第二部分。
When I run this code, nothing shows up. For example I call ind(1, [1, 2, 3])
, but I don't get the integer 13
.
def ind(e, L):
if (e in L == True):
print('13')
else:
print('12')
Operator precedence. If you put (
and )
around e in L
it will work:
def ind(e, L):
if ((e in L) == True):
print('13')
else:
print('12')
ind(1, [1, 2, 3])
But testing for True
can be done (and is the usual idiom) done without the True
def ind(e, L):
if (e in L):
print('13')
else:
print('12')
ind(1, [1, 2, 3])
Edit: as a bonus you can even use True
and False
to keep/nullify things. With your example:
def ind(e, L):
print('13' * (e in L) or '12')
ind(1, [1, 2, 3])
ind(4, [1, 2, 3])
And this ouputs:
13
12
Because e in L
has first been evaluated to True
and 13 * True
is 13
. The 2nd part of the boolean expression is not looked up.
But when calling the function with 4
, then the following happens:
`13` * (e in L) or '12` -> `13` * False or '12' -> '' or '12' -> 12
Becase and empty string evaluates to False
too and therefore the 2nd part of the or
boolean expression is returned.