for ...在范围循环中无法正确创建

时间:2018-04-28 17:01:13

标签: python python-3.x for-loop

所以,我一周前又开始使用python。我试图创建一个返回n的三角形数字的小函数。但是,我在for循环中创造了一个奇怪的故障:

def makeTriangle(s):
    print("S is %d" % s)
    triangle = 0
    for a in range(1,s):
        print("a is: %d " % a)
        triangle = triangle + a
        print("Triangle: %d " % triangle)
        return triangle

n = 3 while n < 10:
    x = makeTriangle(n)
    n+=1

当我运行它时,永远不会从值1更改 - 即使我认为我创建的列表会迭代到&#39; n&#39;。我哪里错了?

1 个答案:

答案 0 :(得分:2)

def makeTriangle(s):
    print("S is %d" % s)
    triangle = 0
    for a in range(1,s):
        print("a is: %d " % a)
        triangle = triangle + a
        print("Triangle: %d " % triangle)
    return triangle

n = 3 
while n < 10:
x = makeTriangle(n)
n+=1 

将你的return语句从for循环中删除