Home > Software engineering >  While True and condition statements
While True and condition statements

Time:09-17

I am trying to get the answer m = [0, 2, 0, 4, 0]:

m = []
while True:
    for x in range(1, 6):
        if x == 2:
            m.append(x)
            continue
        else:
            m.append(0)
            continue
        if x == 4:
            m.append(x)
            continue
        else:
            m.append(0)
            continue
    break

print(m)

Answer is coming m = [0, 2, 0, 0, 0]

CodePudding user response:

Main issue is you need to use elif. You also don't need the while loop.

m = []
for x in range(1, 6):
    if x == 2:
        m.append(x)
    elif x == 4:
        m.append(x)
    else:
        m.append(0)

print(m)

But this really seems like all you need to do is check if the value is divisible by 2:

m = []
for x in range(1, 6):
    if x % 2 == 0:
        m.append(x)
    else:
        m.append(0)

print(m)

With a list comprehension:

print([x if x % 2 == 0 else 0 for x in range(1, 6)])

CodePudding user response:

The continue statements are interfering with your conditions. You should either use them without the else or only use if/elif/else:

if x == 2:
   m.append(x)
   continue
if x == 4:
   m.append(x)
   continue
m.append(0)

OR

if x == 2:
   m.append(x)
elif x == 4:
   m.append(x)
else:
   m.append(0)

and, given that you are doing the same thing when x is 2 as when x is 4, you can use an or relation to minimize code duplication:

if x == 2 or x == 4:
   m.append(x)
else:
   m.append(0)
  • Related