How to Run Your First Python Script in VS Code: A Beginner's Guide

python dev.to

Getting started with coding can feel overwhelming, but setting up your environment doesn't have to be. In this quick tutorial, we will walk through exactly how to set up Visual Studio Code (VS Code) and run your very first Python script from scratch.

Prerequisites
Before we start, make sure you have:

  • VS Code installed on your computer
    .

  • Python downloaded and installed from the official website.

Step 1: Open VS Code and Create a New File
First, launch VS Code on your desktop.

  • Click on File in the top menu and select New File or press Ctrl + N on Windows / Cmd + N on Mac to open a blank text sheet.

  • Save the file immediately by naming it hello.py. Crucial tip: The .py extension tells VS Code that we are writing Python code

Step 2: Install the Python Extension

To make it easier, VS Code needs to understand Python syntax.

  • On the left sidebar, click on the Extensions icon (it looks like four squares).

  • Search for "Python" and click the blue Install button on the official extension by Microsoft.

Step 3: Write Your First Line of Code

Now, go back to your hello.py file. Let's write the classic starter code.Type out the following line:

print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode
  • print() just tells the computer to show whatever text is inside the quotation marks on the screen

Step 4: Run the code!

It's time for the moment.

  • Look at the top-right corner of your screen. Click the Play button (Run Python File). Your terminal will pop up at the bottom, and you will see the words 'Hello, World!' printed out!

Troubleshooting: What if the Run Button Doesn't Work?

When you click the play button, you might see an error in your terminal saying something like "python is not recognized" or a terminal execution hurdle. Don't panic! This just means VS Code doesn't know where Python is hiding on your computer.

How to fix it:
Look at the very bottom right-hand corner of your VS Code window. You will see a small label showing the current Python version (e.g., Python 3.x.x).

  • Click on that version label. A menu will drop down at the top of your screen called "Select Interpreter".

  • Choose the option that says "Recommended" or points directly to the global path where you downloaded Python.
    Once you select the correct interpreter, kill your current terminal session by clicking the little trash can icon in the terminal panel and click the Play button again. It will run perfectly!

Conclusion
You've executed your first Python program in VS Code. From here, you can start experimenting with variables, loops, and building your own cool scripts.

Source: dev.to

arrow_back Back to Tutorials