无法分配给操作员 [英] Can't assign to operator

查看:65
本文介绍了无法分配给操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i = 0
num = 0
while i <= 1000:
    if i % 3 and i % 5 == 0:
        num + i = num <--- Adding Up Numbers Divisable by 3 & 5...
    i += 1
print num

错误:* 不能分配给运算符(第 5 行)

Error:* can't assign to operator (line 5)

推荐答案

您确定不想要:

num = num + i

或等效地:

num += i

?

请注意,使用 sumrange 和生成器表达式可以更轻松地完成此操作:

Note that this can be done a little easier using sum, range and a generator expression:

sum( x for x in range(0,1000,5) if x % 3 == 0 )
                            #^only take every 5th element (0, 5, 10, 15 ...)
                                    #^ Also only take elements divisible by 3

如果您打算仅在 python 2.x 上运行此代码,则可以将上述表达式中的 range 更改为 xrange.另外,在阅读其他人的代码时,有时您会看到 if x % 3 == 0 在这种类型的上下文中写成 if not x % 3,但我更喜欢第一个版本(对我来说似乎更明确一些).

If you're planning on running this code on only python 2.x, you can change range to xrange in the above expression. Also, when reading other people's code, you'll sometimes see if x % 3 == 0 written as if not x % 3 in this type of context, but I prefer the first version (it seems a little more explicit to me).

这篇关于无法分配给操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆