Butterfly Fiziks
Butterfly Fiziks

Reputation: 17

appending an array in while loop and if condition

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.

Upvotes: 0

Views: 2040

Answers (2)

eshirvana
eshirvana

Reputation: 24603

also you know you can do it without loop :

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

Upvotes: 1

jezza_99
jezza_99

Reputation: 1095

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)

Upvotes: 0

Related Questions