Blokebuster
Blokebuster

Reputation: 3

Why is my counter in python not working?

I have just started learning Python and I need to make a list of certain values. See code below. My counter doesn't seem to be working however. It just takes the first num and doesn't change it. For instance, when I try size 5, I get a list of all 25, instead of 25 24 23 22 ... My counter isn't doing anything. I've tried placing it elsewhere in the code, but nothing changes. Any help?

def listmaker(size):   
    listsize = size * size
    list = []
    for i in range(size):
        for j in range(size):
            counter = 0
            num = listsize - counter
            if number > 0 :
                elem = num
                list.append(elem)   
            elif number == 0:
                elem = "X"     
    counter = counter + 1  
    print(list) 

output I get with for instance 4 as size:

16 16 16 16 16 16 16 16 16....(times 16)

what I want it to be:

16 15 14 13 12 11 10 9...

Upvotes: 0

Views: 3745

Answers (3)

internet_user
internet_user

Reputation: 3279

Move counter = 0 to before the loop, so that it is only run once, and move the counter = counter + 1 (equivalent to counter += 1 by the way) to the end of the second loop so it is run repeatedly after everything else.

Also, your elif number==0: is useless, because the loop will be run only 25 times, and that would activate after 26 times.

If you want do do this effectively, you could just use list(range(size**2, 0, -1))

Upvotes: 1

Patrick Haugh
Patrick Haugh

Reputation: 61063

If you're just trying to get integers from size squared to one, just do

list(range(size**2, 0, -1))

The -1 step tells range to count down. Use range(size**2, -1, -1) if you want the list to stop at 0 instead of 1

Upvotes: 1

Hao  XU
Hao XU

Reputation: 352

all your errors are in the comments

def listmaker(size):   
    listsize = size * size
    list = []
    # you should init counter outside the loops
    counter = 0
    for i in range(size):
        for j in range(size):
            num = listsize - counter
            # number -> num
            if num > 0 :
                elem = num
                list.append(elem) 
            # number -> num  
            elif num == 0:
                elem = "X"   
            # you should modify the counter in the loop  
            counter = counter + 1  
    print(list) 

Upvotes: 1

Related Questions