简体   繁体   中英

Why doesn't this nested loop work?

I'm trying to generate a list of triangular numbers (numbers that are the sum of previous numbers 3 = 2 + 1, 6 = 3 + 2 + 1 etc.) But for some reason, the nested loop never get iterated

triangulars = []
for i in range(1, 1000):
    sum = 0
    for j in range(i, 0):
        sum += j
triangulars.append(sum)  
print(triangulars)

because range(i,0) is empty when i >= 0

change for j in range(i,0) to for j in range(i,0,-1)

另外,您还需要在第一个循环(对于i ...)中推入triangulars.append(sum) )。

It looks like there are two small bugs in your code. First range(i, 0) is going to return an empty list if i >= 0 , maybe you want range(0, i) or range(i, 0, step=-1) , I think in this case either of those would work. Second it looks like your indentation is off on the line triangulars.append(sum) . Right now it's outside both loops, I think you want it inside the first loop.

Also you don't need a double loop for this problem, you can just do something like:

def make_triangulars(N):
    triangulars = []
    last = 0
    for i in range(1, N):
        last += i
        triangulars.append(last)
    return triangulars

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM