条件中的分配

时间:2014-10-22 17:13:13

标签: python syntax variable-assignment

在类C语言中,我们可以编写一个这样的循环:

while ( a = func(x) ){
    // use a
}

Python中是否有任何语法可以执行相同的操作?

3 个答案:

答案 0 :(得分:3)

没有直接的等价因为Python中的assignments are statements,而不是C中的表达式。

相反,您可以这样做:

a = func(x)      # Assign a
while a:         # Loop while a is True
    # use a
    a = func(x)  # Re-evaluate a

或者这个:

while True:      # Loop continuously
    a = func(x)  # Assign a
    if not a:    # Check if a is True
        break    # Break if not
    # use a

第一个解决方案是代码较少,但我个人更喜欢第二个解决方案,因为它可以避免重复a = func(x)行。

答案 1 :(得分:0)

没有python没有这个,因为你打开了自己的错误,如

if usr = 'adminsitrator':
    # do some action only administrators can do

您真正意味着==而不是=

答案 2 :(得分:0)

Python不允许在布尔表达式的位置进行赋值。 “pythonic”的方法是:

def func(x):
    if goodStuff:
        return somethingTruthy
    else:
        return somethingFalsey

a = func(x)
while a:
    # use a
    a = func(x)