开发者

how do I create an indented block in Python? [closed]

开发者 https://www.devze.com 2023-01-15 16:06 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_开发知识库 Closed 12 years ago.

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消