最初の 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 を開いたら、Hello, World というメッセージを表示するための Python ファイルを作成します。

  1. [エクスプローラー] ビューの [HELLO_WORLD] パネルで、タイトル バーの上にマウス ポインターを移動し、[新しいファイル] を選択します。

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

  2. 新しいテキスト ボックスに、新しいファイルの名前として「hello.py」と入力して Enter キーを押します。

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

    .py というファイル拡張子を使うことで、このファイルを Python プログラムとして解釈し、内容を Python 拡張機能で評価するよう、VS Code に指示します。

  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 アプリケーションを作成しました。