Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Logic in Python Around and Around

Jeffrey Lee
Jeffrey Lee
493 Points

While loop & continue

I want to get the result of: [5, 4, 2, 1] with the code below, but the code keep running without showing the result

start = 5
list = [ ]
while start:
    if start == 3:
       continue #
   list.append(start)
   start -= 1

print(list)

However if i use break, i can get a result: [5, 4] with the code below.

start = 5
list = [ ]
while start:
   if start == 3:
      break #
   list.append(start)
   start -= 1

please advise if there is a way for me to achieve [5, 4, 2, 1] with while loop or another other way

thank you

Jeffrey Lee
Jeffrey Lee
493 Points

I found work around!!! But i still dont know why the continue doesn't work

start = 5
list = [ ]
while start:
    if start != 3:
        list.append(start)
    start -= 1

print(list)

1 Answer

Jeffrey,

You're very close. There are several ways to do this, of course, but remember that even if the number is 3, you still want to decrement the count before returning to the top of the while loop. So:

start = 5
list = [ ]

while start:
   if start == 3:
       start -= 1
       continue
   list.append(start)
   start -= 1

print(list)