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!

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


2,330 Points

" : " what it can do and why

Good morning my fellow pythons.

I was just recently racking my brain over a 'break' code challenge when i noticed that I was using multiple semicolons in my code blocks.

def loopy(items): for item in items: if item == "STOP": break print(item)

Now maybe I missed it in a past lesson or maybe I just understood their use # probably a little of both #

Can some one give me a quick refresher on the use of ' : ' in python code?


1 Answer

Hi Andy,

With me looking at your JS points, I think you know a bit JavaScript.

I'm assuming you know what a block is in JS. Quick overview, in case you forgot: a block is a piece of code inside of {}. For example, with a if clause, the block is only run if the condition is true.

In Python, you don't use {} to make a block. You use a colon.

Example in JS:

if (1 > 2) {
    alert("This won't be printed because 1 is never greater then 2");

Same example in Python:

if 1 > 2:
    print("This won't be printed because 1 is never greater then 2")

Since JS uses braces, you don't need to indent. To mark the end of the block, you use the closing curly brace }

if (1 > 2) {
alert("Look, no indentation!");

You can even do this in JS:

if (1 > 2) { alert("All on one line!"); }

You are allowed to do this because you can start the block with { and end the block with }. In Python, however, you don't use { to mark the beginning of the block and } to mark the end of the block.

To mark the beginning of the block, you use :, AKA a colon. There are no symbol to mark the end of the block.

To represent code in a block, you have to use indentation, or spacing. If you write this:

if 1 > 2:

Python will cause an error because it thinks that there are no block for the condition and the printing part is outside of the block.

If you fix it:

if 1 > 2:

Python will understand that the printing is in the if condition's block.

I hope this makes sense. :grin:

If you have any more questions, please ask below.

Happy C0D1NG! :tada:

:dizzy: ~Alex :dizzy:

No problem :smiley: