Python Tutorial / Write and Run Python in VS Code
Running Python in VS Code requires both an editor setup and an interpreter selection. Open the project folder and choose its virtual environment so that running code and installing packages use the same Python.
Prepare the editor and project folder
This guide assumes that Python is installed and that your project has a .venv environment. VS Code is an editor; installing it does not replace installing an interpreter. In Extensions, locate Microsoft’s Python extension and verify its publisher before installation.
For the relevant APIs and platform requirements, see Write and Run Python in VS Code documentation.
Use File → Open Folder to open python-lab instead of opening only an individual file. This helps align the terminal’s working directory and relative file paths with the project root.
Select and verify the interpreter
- Open the Command Palette and run Python: Select Interpreter.
- Choose the Python executable in the project’s .venv folder, or enter its path if it is missing from the list.
- Open a new terminal and check the executable and pip location.
python -c "import sys; print(sys.executable)" python -m pip --version
Expect .venv\Scripts\python.exe on Windows or .venv/bin/python on macOS and Ubuntu. An existing terminal may retain its previous environment after an interpreter change, which is why the new terminal check matters.
Run a complete script
Save the complete code below as expense.py in a separate practice folder, using UTF-8. Run python expense.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.
amounts = [3500, 8000, 2500]
total = sum(amounts)
print(f"total={total}")
Expected output:
total=14000
Compare normal execution with debugging
Save the file and use the Python extension’s Run Python File command. Place a breakpoint on the line after total is calculated, then start debugging the Python file. Inspect amounts and total in the variables pane and step through execution. The value in the debugger should agree with the printed total.
If an import fails after installation, compare the interpreter and pip paths. If a file cannot be opened, check the working directory and filename. If edited code seems unchanged, confirm that you saved it and ran the intended file. Avoid filenames such as json.py or csv.py, which can shadow standard-library modules.
Other extensions may provide run buttons with different execution settings. Start with the Python extension’s commands and the selected project terminal, then investigate any differences explicitly.






