我不知道';我不明白为什么Python代码会这样执行![欧拉计划]

我不知道';我不明白为什么Python代码会这样执行![欧拉计划],python,Python,我刚刚完成Euler项目,Python的第一个问题。。。链接如下: 我用python提出了以下解决方案 #!/usr/bin/env python def main(): print("The answer will be calculated shortly...") if __name__ == "__main__": main() n = 1000 n=-1 def isMultiple(i): if (i % 3 == 0) or (i % 5 == 0

我刚刚完成Euler项目,Python的第一个问题。。。链接如下:

我用python提出了以下解决方案

#!/usr/bin/env python

def main():
    print("The answer will be calculated shortly...")

if __name__ == "__main__":
    main()

n = 1000
n=-1

def isMultiple(i):
    if (i % 3 == 0) or (i % 5 == 0):
        if (i % 3 == 0) and (i % 5 == 0):
            return False
        else:
            return True


sum = 0
for i in range(3, n):
    if isMultiple(i):
        sum+=1
    print("The answer is... ", sum)
但是,在运行此解决方案时给出的所有信息是:

[arch@archlinux Project Euler]$ python 1000-multi3or5.py
The answer will be calculated shortly...
[arch@archlinux Project Euler]$ 

我真的不明白出了什么问题,你能帮我解释一下为什么吗?非常感谢您花时间阅读本文,尤其是如果您费心帮助我的话。:)

因为循环从未发生:

n = 1000
n=-1
最后:

for i in range(3, n):
您运行的范围为3到-1

In [4]: range(3, -1)
Out[4]: []
将行更改为:

n -= 1
它应该起作用:

In [9]: n = 20 # Just to show a smaller output - your n would be 999 obviously
   ...: sum = 0
   ...: for i in range(3, n):
   ...:     if isMultiple(i):
   ...:         sum+=1
   ...:     print("The answer is... ", sum)
   ...:     
('The answer is... ', 1)
('The answer is... ', 1)
('The answer is... ', 2)
('The answer is... ', 3)
('The answer is... ', 3)
('The answer is... ', 3)
('The answer is... ', 4)
('The answer is... ', 5)
('The answer is... ', 5)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 7)
('The answer is... ', 7)

所以设置n=-1,当然for循环执行零次。当心:)哦,天哪,我真蠢p你的程序不检查命令行参数。然后你想做n-=1你设置了
n=-1
,然后当
range(3,n)
被调用时,它就不会进入循环(也不会打印任何东西)。我没有意识到我这么做了。现在我觉得自己很愚蠢。谢谢你帮助大家!没问题-打字错误总是会让人抓狂,尤其是当它仍然是有效代码的时候!是的,你强调了我对垃圾邮件的另一个问题。。。哎呀,我也修好了。今天不太好,干得好,先生,你真的帮了我很多