1

How to create an indented block in Python?

 2 years ago
source link: https://www.codesd.com/item/how-to-create-an-indented-block-in-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to create an indented block in Python?

advertisements

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"


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK