我不明白为什么这个Python代码会这样执行![欧拉项目]

2024-09-28 05:21:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

http://projecteuler.net/problem=1

我想出了下面的解决方案,在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)

但是,在运行此解决方案时,给出的所有信息是:

^{pr2}$

我真的不明白出了什么问题,你能帮我解释一下为什么吗?如果你能抽出时间来阅读这篇文章,特别是如果你愿意帮助我,我将不胜感激。:)


Tags: the项目answerhttpreturnif链接main
1条回答
网友
1楼 · 发布于 2024-09-28 05:21:20

因为循环永远不会发生:

n = 1000
n=-1

最后:

^{pr2}$

你的范围是从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)

相关问题 更多 >

    热门问题