建立您的第一個 Python 應用程式

已完成

安裝 Python 和 Python 工具之後,就可以建立您的第一個 Python 應用程式! 在本練習中,您將建立空的資料夾,在 Visual Studio Code 中開啟資料夾,然後建立您的第一個應用程式。

步驟 1 - 在專案資料夾中啟動 VS Code

許多專案都從空的資料夾開始,這就是您的起點。

  1. 在 Visual Studio Code 中選取 [終端機]>[新增終端機] 來開啟一個新的終端機視窗。

  2. 建立名為「hello-world」的空白資料夾、瀏覽至該資料夾,然後輸入下列命令,開啟該資料夾中的 VS Code (程式碼)(.):

    1. 建立名為 hello-world 的新資料夾:

      md hello-world
      
    2. 瀏覽至 hello-world 資料夾:

      cd hello-world
      
    3. 在該資料夾中開啟 Visual Studio Code:

      code .
      
    1. 建立名為 hello-world 的新資料夾:

      mkdir hello-world
      
    2. 瀏覽至 hello-world 資料夾:

      cd hello-world
      
    3. 在該資料夾中開啟 Visual Studio Code:

      code .
      
    1. 建立名為 hello-world 的新資料夾:

      mkdir hello-world
      
    2. 瀏覽至 hello-world 資料夾:

      cd hello-world
      
    3. 在該資料夾中開啟 Visual Studio Code:

      code .
      

    提示

    以系統管理員身分開啟命令提示字元或終端機以執行 code .

    或者,您可以透過作業系統 UI 執行 VS Code,然後使用 [檔案 > 開啟資料夾] 來開啟專案資料夾。

步驟 2 - 建立新的 Python 檔案並新增程式碼

在 Visual Studio Code 開啟空的資料夾後,現在要建立 Python 檔案來顯示訊息 Hello, World。

  1. 在 [總管] 檢視中,將滑鼠停留在 HELLO_WORLD 面板的標題列,然後選取 [新增檔案]

    Screenshot of the Visual Studio Code Explorer window with New File highlighted.

  2. 在新的文字方塊中輸入並按下 Enter 鍵,將新檔案命名為 hello.py

    Screenshot of Explorer window with hello.py entered for new file.

    使用 .py 副檔名,您便告訴 VS Code 將此檔案解譯為 Python 程式,以便評估具有 Python 副檔名的內容。

  3. 在編輯器面板中輸入下列 Python 程式碼。 此命令使用 print 函式,在應用程式執行時顯示 Hello, World! 文字。

    print('Hello, World!')
    
  4. 選取 [檔案][儲存] (或 Ctrl+S) 來儲存檔案。

    Screenshot of file menu with Save highlighted.

步驟 3:執行應用程式

因為這是單行程式,所以您可以從 Visual Studio Code 內實際執行應用程式。

  1. 選取 [檢視] 和 [終端機],在 Visual Studio Code 中開啟內建的終端機。

    Screenshot of view menu with Terminal highlighted.

  2. 在新的終端視窗中執行下列命令,以執行您的 Python 程式碼。

    python hello.py
    
    python3 hello.py
    
    python3 hello.py
    

    Screenshot of running the Python code.

    Hello, World! 在終端機視窗中顯示。 恭喜! 您已建立 Python 應用程式!