2014-12-04 148 views
-1

计划1

list=[1,2,3,4] 
A=3 in list 
if A: 
    print('True') 

计划2

list=[1,2,3,4] 
if A=3 in list: 
    print('True') 

所以我有这两个程序使用一个布尔值。程序1运行正常,我明白为什么,但程序2没有。我认为,因为A=3 in list返回true或false,你可以把它作为if循环的一部分嵌入,但我猜不是。这是为什么?这里发生了什么?在程序中嵌入在if语句

+0

您试图在if条件中分配值。我认为这是无效的。 – 2014-12-04 07:14:48

+0

可能的重复http://stackoverflow.com/questions/2603956/can-we-have-assignment-in-a-condition – Sriram 2014-12-04 07:18:14

+0

官方文档中的这一部分将很有用 - https://docs.python.org/ 2/tutorial/datastructures.html#more-on-conditions where it states that _“请注意,在Python中,与C不同,赋值不能在表达式内部发生,C程序员可能会对此抱怨,但它避免了遇到的一类常见问题C程序:当==意图时,在表达式中键入= _ – Sriram 2014-12-04 07:19:25

回答

0

看评论:

计划1个

list=[1,2,3,4] 
# 3 in list evaluates to a boolean value, which is then assigned to the variable A 
A=3 in list 
if A: 
    print('True') 

计划2

list=[1,2,3,4] 
# Python does not allow this syntax as it is not "pythonic" 
# Comparison A == 3 is a very common operation in an if statement 
# and in other languages, assigning a variable in an if statement is allowed, 
# As a consequence, this often results in very subtle bugs. 
# Thus, Python does not allow this syntax to keep consistency and avoid these subtle bugs. 
if A=3 in list: 
    print('True') 
3

if A=3 in list:无效语法。您可能正在寻找原始布尔表达式,而不是if 3 in list

另外,不要使用list作为变量名称。您将会覆盖Python提供的实际list方法。

0

它的简单,你不能使用assignmnent操作如果

喜欢这里

A=3 

蟒蛇将它读成assignmnent,并抛出错误

0

第一个例子是等价于:

A = (3 in list) 
#i.e. A is boolean, not an integer of value 3. 

第二个例子只是无效的语法。