2010-09-12 118 views
0

例如,我如何在Python中輸入以便正確縮進?如何在Python中創建縮進塊?

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

也許你的意思是'1 + 1 == 2'? – 2010-09-12 17:48:04

+4

不要混合使用空格和製表符 – 2010-09-12 17:50:12

+0

您使用的是什麼IDE? – mpen 2010-09-12 18:02:18

回答

4

這是正確縮進。

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

如果你正在使用Python的REPL ...只是第一行之前輸入空格,並將對縮進的行空間任意但一致的號碼(標準是空格)塊內。

編輯:按要求添加 -

由於你的背景是在Java中,你可以大致等同蟒蛇爲塊到Java的使用大括號縮進規則。例如,一個else語句可以添加像這樣:

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

你甚至可以,如果你選擇,模仿「bracist」(如pythonistas colloquialy叫他們)語言,評論,以幫助您可視化 -

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

簡而言之,通過更改縮進級別,可以更改塊深度。

我不能強調閱讀諸如Section 4.8中突出顯示的PEP8等文檔的重要性,或者有關Python中縮進基本規則的其他任何文檔的任何數量的文檔的重要性。

+0

另外,請參閱Python教程的第3.2節(http://docs.python.org/tutorial/introduction.html)和4.8(http://docs.python.org/tutorial/controlflow.html)關於「適當」縮進的討論。 – sleepynate 2010-09-12 17:51:47

+0

我使用Idle作爲我的IDE。如何終止塊,以便我可以添加一個「其他」語句?我習慣於使用大括號作爲分隔符的Java。 – javaguy 2010-09-12 18:32:10

+1

@javaguy:在Python中沒有大括號,唯一的塊分隔符是縮進。因此,要指定「if」塊的結尾,只需縮進代碼並將「else」語句與「if」相同。 – MatToufoutu 2010-09-12 19:47:26