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

Mengqi Liu
Mengqi Liu
875 Points

While Loop: example Countdown

countdown = 5 while countdown: ... print(countdown) ... countdown -= 1 ...print ("happy new year") File "<stdin>", line 4 print("happy new year!") SyntaxError: invalid syntax

so if I want to have a happy new year appears immediately after the countdown " 54321 happy new year", so where should I put 'print("happy new year")'??? How can I deal with the syntaxerror? Thanks a lot.

4 Answers

Bryan Dobberstein
Bryan Dobberstein
16,361 Points

Only the two lines within the while loop should be indented. The rest should not.

countdown = 5

while (countdown != 0):
  print(countdown)
  countdown -= 1

print("Happy New Year")
countdown = 5

while (countdown != 0):
  print(countdown)
  countdown -= 1

  if (countdown == 0):
    print("Happy New Year")

Hope this helps.

Bryan Dobberstein
Bryan Dobberstein
16,361 Points

You really don't need the if statement.

countdown = 5

while (countdown != 0):
  print(countdown)
  countdown -= 1

print("Happy New Year")
Mengqi Liu
Mengqi Liu
875 Points

hi, thanks for the code. It works, I just need to pay attention to the indentations.

Yes i think you are right. I am confusing the JS syntax with python

Bryan Dobberstein
Bryan Dobberstein
16,361 Points

Only one way to tell, run it. I wouldn't have posted if I hadn't tested it first.

Mengqi Liu
Mengqi Liu
875 Points
          <p>countdown = 5
                while(countdown != 0) :
                     print(countdown)
                     countdown -=1
                print("Happy New Year")</p>
          ```

I still can't get it, why it shows that for the last line, there is an invalid syntax. 
How can you separate print("Happy New Year") from the block above? and I am really bad at the indentations. 
Thanks.