简体   繁体   中英

Nested "for" loop will not change variable within loop

        for a in range(0,2):
            for x in range (0,16):
                bombs.append(((40*x),(40*a),39,39))

This is my first question on this site and i'm pretty new to python so any tips and simple explanation would be greatly appreciated!

As said in the title i cannot seem to change the "a" variable in the .append. The output i receive is this:

(0, 0, 39, 39) (40, 0, 39, 39) (80, 0, 39, 39) (120, 0, 39, 39) (160, 0, 39, 39) (200, 0, 39, 39) etc....

(0, 0, 39, 39) (40, 0, 39, 39) (80, 0, 39, 39) (120, 0, 39, 39) (160, 0, 39, 39) (200, 0, 39, 39) etc...

The first set is obviously correct but when it loops over again the variable stays at 0 instead of being the value of 40*a!

I'm hoping that i'm making a simple error! Thank you

update with full code:

def bomb():
    global bombs
    bombs=[]

    for a in range(0,2):
        for x in range (0,16):
            bombs.append(((40*x),(40*a),39,39))
            print bombs[x]

These are nested loops. Your inner loop

for x in range (0,16):

will iterate 16 times during the first iteration of the outer loop. Only after these 16 iterations where only x changes, will a change for the first time!

[..., (600, 0, 39, 39),  (0, 40, 39, 39), ...]

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