Home > Net >  appending an array in while loop and if condition
appending an array in while loop and if condition

Time:11-26

n = -12
while n < 15:
    if n < 0:
        dgt = []
        dgt.append(n)
    n = n 1
print(dgt)

I am trying to append all negative values in dgt[] but what I get from this code [-1] which is not my result I want all negative valuse in dgt[] please help me.

CodePudding user response:

You are reinitialising the list dgt for every loop iteration. Move it outside the loop.

n = -12
dgt = []
while n < 15:
    if n < 0:
        dgt.append(n)
    n = n 1
print(dgt)

CodePudding user response:

also you know you can do it without loop :

n = -12
dgt = [n i for i in range(-n)]
print(dgt)
  • Related