循环中的Python数组

时间:2014-03-03 00:14:39

标签: python loops annotations

我为这个模糊的名字道歉,我不知道我想要做的具体名称是什么。

我无法让我的功能正常工作。我想要做的是在数组中添加一个数字,如果它在变量newPoint和0之间,然后将该数字从newPoint中取出,直到它小于或等于0.但是当我尝试打印数组时,它是空的。任何帮助将不胜感激。谢谢。

以下是代码:

def setupArray():
    newPoint = 500
    array = []
    if newPoint > 0:
        x = random.randint(1, 500)
        if newPoint > x:
            array.append(x)
            newPoint = newPoint - x
    elif newPoint <= 0:
        print(array)
        return array

1 个答案:

答案 0 :(得分:1)

你没有循环,这应该是你要找的东西:

import random

def setupArray():
    newPoint = 500
    array = []
    while newPoint > 0:
        x = random.randint(1, newPoint)
        array.append(x)
        newPoint = newPoint - x
    return array

print(setupArray())