Python 語法

執行 Python 語法

正如我們在上一節中學習到的,可以直接在命令行中編寫執行 Python 的語法:

>>> print("Hello, World!")
Hello, World!

或者通過在服務器上創建 python 文件,使用 .py 文件擴展名,并在命令行中運行它:

C:\Users\Your Name>python myfile.py

Python 縮進

縮進指的是代碼行開頭的空格。

在其他編程語言中,代碼縮進僅出于可讀性的考慮,而 Python 中的縮進非常重要。

Python 使用縮進來指示代碼塊。

實例

if 5 > 2:
  print("Five is greater than two!")

運行實例

如果省略縮進,Python 會出錯:

實例

語法錯誤:

if 5 > 2:
print("Five is greater than two!")

運行實例

空格數取決于程序員,但至少需要一個。

實例

if 5 > 2:
 print("Five is greater than two!")  
if 5 > 2:
        print("Five is greater than two!") 

運行實例

您必須在同一代碼塊中使用相同數量的空格,否則 Python 會出錯:

實例

語法錯誤:

if 5 > 2:
 print("Five is greater than two!") 
        print("Five is greater than two!")

運行實例

Python 變量

在 Python 中,變量是在為其賦值時創建的:

實例

Python 中的變量:

x = 5
y = "Hello, World!"

運行實例

Python 沒有聲明變量的命令。

您將在 Python 變量 章節中學習有關變量的更多知識。

注釋

Python 擁有對文檔內代碼進行注釋的功能。

注釋以 # 開頭,Python 將其余部分作為注釋呈現:

實例

Python 中的注釋:

#This is a comment.
print("Hello, World!")

運行實例