tags:

views:

621

answers:

7

I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces?

+3  A: 

Yes.

if True:
    #dosomething
else:
    #dosomething else

#continue on with whatever you were doing

Basically, wherever you would've had an opening curly brace, use a colon instead. Unindent to close the region. It doesn't take long for it to feel completely natural.

Skilldrick
+2  A: 

Yup :)

And there's (usually) a difference between 4 spaces and a tab, so make sure you standardize the usage ..

cwap
Highly recommended to uses 4 spaces over tab too, so please change old habits if you currently use tabs :)
Jordan Messina
+10  A: 

Yes. Curly braces are not used. Instead, you use the : symbol to introduce new blocks, like so:

if True:
    DoSomething()
    SomethingElse()
else:
    Something()
Lucas Jones
But better to follow the convention of 98% of Python code and not put that spurious space in front of the colon. The more surprises you throw in front of readers, the more they'll be distracted from the real meaning of the code.
Peter Hansen
Gah. Old habits die hard, eh? Will fix. Thanks :).
Lucas Jones
+2  A: 

Yup. However, you define dictionaries in Python using curly braces:

dict = {
    'key': 'value',
}

Ahhhhhh.

Paul D. Waite
+22  A: 
if foo: #{
    print "it's true"
#}
else: #{
    print "it's false!"
#}

(Obviously, this is a joke.)

Lars Wirzenius
Oh Lars, you funny little man! :)
Kaitsu
You so funny! I think I'm going to do that now every time I use python
Matt S.
So it's possible. cool!
openfrog
@openfrog: no, it's not, these are just single-line code comments... (and he did say it was a joke)
Abel
@Abel is correct. I should have explained the joke in a comment, just in case.
Lars Wirzenius
+15  A: 

You can try to add support for braces using a future import statement, but it's not yet supported, so you'll get a syntax error:

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance
Adam Rosenfield
+2  A: 

As others have mentioned, you are correct, no curly braces in Python. Also, you do not have no end or endif or endfor or anything like that (as in pascal or ruby). All code blocks are indentation based.

miya