Python/基本語法

維基教科書,自由的教學讀本

Hello, World![編輯]

(謹記:以下涉及到的符號均為英文符號)

下面是一個在標準輸出設備上輸出Hello World的簡單程序,這種程序通常作為開始學習程式語言時的第一個程序:

print("Hello, world!")
#Hello, world!

Python 也可以單步直譯執行。執行 Python 直譯器進入互動式命令列的環境,你可以在提示符號 >>> 旁輸入 print "Hello, world!",按 Enter 鍵輸出結果:

>>> print("Hello, world!")
#Hello, world!

print是最簡單,同時是最常用的輸出代碼,因為字句和絕大部分的變量都可以使用print輸出。

輸出字句時,需在頭尾加上'"""",變量時則不用,在變量之間,或者字句和變量之間需要,+作間隔。

print在每次輸出值後,都會開新行,如果想在上一行繼續輸出,可以加上,end=

>>>print('This function does not give a new line. ',end='')
>>>print('See?')
#This function does not give a new line. See?

python一行一句代碼,每句代碼結束後需要開新行。

代碼之間亦需要對齊,代表層級關係。

代碼前如果加上#,該行代碼就不會被執行,可以在測試單獨某個程式時使用,或留下備註給自己或其他人。

>>>print('This line will be shown.') #You can add comments here as well!
>>>#print('This line will not be shown.') This whole line will not be executed.
This line will be shown.