为什么这个if语句总是返回True?

时间:2016-08-09 11:57:03

标签: python-3.x

所以我有这段代码:

steps = 0
biggestSteps = 0
startY = 2
y = startY

def process(x):
    global steps
    steps = steps + 1
    if x % 2 == 0:
        return x/2
    else:
        return (3*x)+1

while True:
    y = process(y)
    if y == 1 or y == 4:
        if steps > biggestSteps:
            biggestSteps = steps
            print("Biggest number yet: " + str(startY) + ", with " + str(steps) + " steps")
            startY += 1
            y = startY
            steps = 0

当我尝试运行此代码时,

if steps > biggestSteps:

将alawys返回True,它将

print("Biggest number yet: " + str(startY) + ", with " + str(steps) + " steps")

对于每个号码,我当然不想要。

我如何制作它只在数字达到最高步数时打印?

编辑:

我尝试添加

global
在while循环中

(很确定它什么都没改变)

steps = 0
biggestSteps = 0
startY = 2
y = startY

def process(x):
    global steps
    steps = steps + 1
    if x % 2 == 0:
        return x/2
    else:
        return (3*x)+1

while True:
    global steps
    global biggestSteps
    global startY
    global y
    y = process(y)
    if y == 1 or y == 4:
        if steps > biggestSteps:
            biggestSteps = steps
            print("Biggest number yet: " + str(startY) + ", with " + str(biggestSteps) + " steps")
            startY += 1
            y = startY
            steps = 0

1 个答案:

答案 0 :(得分:0)

我认为IDLE在复制时犯了一个错误,因为在

if steps > biggestSteps:
            biggestSteps = steps
            print("Biggest number yet: " + str(startY) + ", with " + str(biggestSteps) + " steps")
            startY += 1
            y = startY
            steps = 0

                startY += 1
                y = startY

代码的一部分不得在此if语句中。