![](/img/trans.png)
[英]My code works when not indented and not in a def function in python
[英]Are indented code under an `if` and a `def` both called blocks in Python?
在Python中, def
, class
等關鍵字引入了一個新的范圍 。 其他人,比如if
或for
not - 他們使用封閉代碼的范圍。 (范圍解析在范圍規則的簡短描述中進行了解釋? )
對於這兩種不同類型的關鍵字,“縮進”代碼行的正確術語是什么?
例:
def foo():
do_bar() # indent type 1
do_another_bar() # indent type 1
例2:
if True:
do_something() # indent type 2
do_more_things() # indent type 2
縮進“類型1”和“類型2”都稱為代碼“ 塊 ”嗎?
一般來說,是的,在<keyword-clause>:
下縮進的任何文本部分都稱為“塊”。
C / C ++ / Java / JavaScript / Perl / PHP / etc中花括號內的任何文本部分也是如此。 縮進是Python的大括號。
Python中復合語句的語法將縮進的代碼塊定義為“套件”。 例如:
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
所以,在一個實際例子中:
if True:
print "It's true!"
包含print語句的行(以及該縮進級別內的任何其他行)將是一個套件。
如果將每個級別的縮進視為代碼塊有幫助,那很好。 但是,Python語法將其稱為套件。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.