Python語句、縮進、注釋
在下面的文章中,将學習Python語句,為什麼縮進很重要,如何在程式設計時使用注釋。
Python Statement
Instructions that a Python interpreter can execute are called statements. For example,
a = 1
is an assignment statement.
if
statement,
for
statement,
while
statement etc. are other kinds of statements which will be discussed later.
Python解釋器可以執行的指令,叫做語句。
比如 a = 1是一個指派語句。if語句、for語句、while語句等等是其它類型的語句(後面會講到)。
Multi-line statement
多行的語句
在Python中,用換行符标志一個語句的結束。但是我們可以使用行繼續符(\)使語句擴充到多行。例如
a = 1+2+3+4+\
5+6+7
print(a)
#結果是28
上面這是顯示的行繼續符号的使用。
In Python, line continuation is implied inside parentheses ( ), brackets [ ] and braces { }.(在Python中,行的連續性隐藏在(),[],{}中)
For instance, we can implement the above multi-line statement as(例如,我們可以用這樣的方法實作上面的代碼)
a = (1+2+3+
4+5+6+7)
執行結果也是一樣的。(但要注意,寫代碼的時候,最後一個括号")"要最後寫。否則Python仍然認為換行符是語句結束的标志)
這個代碼是用圓括号"()"做多行的指令。我們也可以用"[]"和"{}"來做,看例子:
colors = ['red','blue',
'yellow',
'green']
print(colors) #結果是['red','green',...]
#感覺不實用
colors = {'red','blue',
'yellow',
'green'}
print(colors) #結果是 set(['red','yellow',...])
我們也可以用分号 " ; "将多行指令放入一行,比如:
a=1; b=2; c=3;
#不建議這麼搞,還是多行好
Python Indentation
Python縮進
大多數程式設計語言如C、C++、Java都使用括号{}來定義一個代碼塊。
Python使用縮進。
代碼塊(函數體、循環等)以縮進開始,以第一行未縮進結束。縮進量由您決定,但必須在整個塊中保持一緻。
通常四個空格用于縮進,并且優先于制表符。
for i in range(1,11):
print(i)
if(i==5):
break
在Python中強制縮進使代碼看起來整潔幹淨。這個結果将使Python程式看起來相似且一緻。
不正确的縮進将導緻:IndentationError
Python Comments
Python注釋
Comments are very important while writing a program. It describes what's going on
inside a program so that a person looking at the source code does not have a
hard time figuring it out. You might forget the key details of the program you just
wrote in a month's time. So taking time to explain these concepts in form of
comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
在程式設計時注釋非常重要。注釋描述了程式的功能,是以當一個人讀源碼時不必花費很多精力來搞明白這段代碼到底是幹嘛的。
寫的代碼在一個月以後,可能就忘了關鍵性的細節了。花時間寫注釋是非常有幫助的。
在Python中,我們用 "#"開始寫注釋。"#"這個隻能寫一行注釋。換行時需要另寫"#"。
注釋是為了讓程式員更好地了解程式。Python解釋器忽略注釋(Python Interpreter ignores comment)。
#This is a comment
#print out hello
print('hello')
Multi-line comments
一次性寫多行注釋。(上面的都是單行注釋。内容多時明顯不友善)
我們可以用三重引号(triple quotes)寫多行注釋 (''') (""")
這些三重引号通常用于多行字元串。但它們也可以用作多行注釋。除非它們不是docstring(是doc string?),否則不會生成任何額外的代碼?(DocStrings見連結:《Python DocStrings》)
#三重引号拼寫多行字元串
name = '''tom,jerry,
xiaoming'''
print(name) # 結果是這樣: tom,jerry,\nxiaoming
#注意結果中有 \n
"""This is also a
perfect example of
multi-line comments"""