views:

146

answers:

2

for example, how to I enter this in Python so that it is indented correctly?

if 1 + 2 == 2:
   print "true"
   print "this is my second line of the block"
   print "this is the third line of the block"
+4  A: 

This is correctly indented.

if 1 + 2 == 2:
    print "true"
    print "this is my second line of the block"
    print "this is the third line of the block"

If you're using python's REPL... simply enter no spaces before the first line, and an arbitrary but consistent number of spaces for indented lines (standard is for spaces) within the block.

Edit: added per request --

Since your background is in Java, you could roughly equate pythons indentation rules for blocks to Java's use of curly braces. For example, an else statement could be added like so:

if thisRef is True:
    print 'I read the python tutorial'
else
    print 'I may have skimmed a blog about python'

You could even, if you choose, mimic a "bracist" (as pythonistas colloquialy call them) language with comments to help you visualize --

if thisRef is True: # {
    print 'I read the python tutorial'
# }
else # {
    print 'I may have skimmed a blog about python'
# }

Put simply, by changing indentation levels, you change block depth.

I cannot emphasize enough the importance of reading such documents as PEP8, which is highlighted in Section 4.8, or any number of other pieces of documentation on the basic rules of indentation in python.

sleepynate
Also, check out section 3.2 (http://docs.python.org/tutorial/introduction.html) and 4.8 (http://docs.python.org/tutorial/controlflow.html) of the Python tutorial for a little discussion on "proper" indentation.
sleepynate
I am using Idle as my IDE. How eo I terminate the block so I can add an "else" statement? I am used to Java where we use curly braces as delimiters.
javaguy
@javaguy: in python there are no curly braces, the only blocks delimiter is the indentation. Therefore, to specify the end of your "if" block, just dedent your code and put your "else" statement at the same level as the "if".
MatToufoutu
+1  A: 

Indenting in Python "Correctly" means "consistently".

"Note that each line within a basic block must be indented by the same amount." Reference

http://docs.python.org/tutorial/controlflow.html#intermezzo-coding-style summarizes the rest of the things you need to do to write "correct" Python as per PEP-8

Tim Bielawa