为什么我的 Python 脚本根本不起作用?

Why does my Python script not work at all?

我正在为一个叫做 'Project Euler' 的东西编写这段代码,它基本上是一个 maths/computer 在线科学东西,link 可以在 here 中找到:

所以无论如何,当我 运行 我的代码在 Python 3.5 中时,它在 shell 中除了光标位 blink 什么都不做秒。 这是有问题的代码:

`mylist=[]
a=1
b=2
c=a+b
def fib():
    a=1
    b=2
    c=a+b
    a=b
    b=c
    c=a+b
if a%2==0:
    mylist.append(a) and print(a)
elif b%2==0:
    mylist.append(b) and print(b)
elif c%2==0:
    mylist.append(c) and print(c)
else:
    print(end='')
while a and b and c<4000000:
    fib()
print(sum(mylist))'

我要回答的问题是

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

该代码旨在将最多 400 万的斐波那契数字添加到列表中,然后打印它们的总和,这将完美地回答问题,但它似乎不起作用。

您在这里创建了一个无限循环:

while a and b and c < 4000000:

这将转换为 "while a is truthy and b is truthy and c is less than 4000000",并且它将始终是 True,因此您的 while 循环将永远不会终止。 "truthy" 的意思是: bool(value) return True 吗?如果是这样,那么 value 就是 "truthy"。所以 1'hello'[] 等是真的,而 0False[] 等不是 (他们是 "falsey")。我不会评论你所有的逻辑,因为你会从自己解决问题中获益更多。但是,这里有一些可以帮助您摆脱困境的提示:

  1. 如果你想检查 abc 所有 小于 4000000,你可以这样做:

    while a < 4000000 and b < 4000000 and c < 4000000:
    

    或更简洁:

    while all(i < 4000000 for i in [a, b, c]):
    
  2. 为了不产生无限循环,您需要确保 abc 大于 4000000在你的程序中的某个时刻通过 incrimination 他们的价值观。您在 abc 内部 中进行的数学运算,您的 fib() 函数仅处理三个名为 [=23= 的变量]、bc 是该函数的局部变量;它不会更改该函数的 abc outside 的值。