2. Install Python & VS Code: Run Your First Script
This tutorial provides a comprehensive guide for beginners to install Python, set up Visual Studio Code (VS Code), create a virtual environment, and run your first Python script. It includes step-by-step instructions, code examples, and troubleshooting tips to ensure a smooth experience.
1. Install Python
Python is a popular programming language used for web development, data analysis, automation, and more. Follow these steps to install Python on your operating system:
Windows:
• Download the latest Python installer from https://www.python.org/downloads/
• Run the installer and check the box ‘Add Python to PATH’ before clicking Install.
• Verify installation by opening Command Prompt and typing:
python –version
python -m pip –version
macOS:
• Install Homebrew if not already installed: /bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)”
• Install Python using Homebrew:
brew install python
• Verify installation:
python3 –version
python3 -m pip –version
Linux (Ubuntu/Debian):
- Update package list and install Python:
sudo apt update
sudo apt install python3 python3-pip
- Verify installation:
python3 –version
python3 -m pip –version
2. Create and Activate a Virtual Environment
A virtual environment isolates your project dependencies. This prevents conflicts between packages across different projects.
Steps:
• Create a virtual environment:
python -m venv .venv
• Activate the virtual environment:
Windows (CMD): .\.venv\Scripts\activate
Windows (PowerShell): .\.venv\Scripts\Activate.ps1
macOS/Linux: source .venv/bin/activate
- • Upgrade pip:
python -m pip install –upgrade pip
3. Install VS Code and Python Extension
Visual Studio Code is a lightweight, powerful code editor. Install VS Code from https://code.visualstudio.com/. After installation:
• Open VS Code and install the Python extension by Microsoft.
• Select the interpreter from your virtual environment using ‘Python: Select Interpreter’.
4. Write and Run Your First Python Script
Create a file named hello.py and add the following code:
print(‘Hello, world!’)
name = input(“What’s your name? “)
print(f’Nice to meet you, {name}!’)
Run the script from the terminal:
python hello.py
5. Debugging in VS Code
• Set a breakpoint in hello.py.
• Press F5 to start debugging and choose ‘Python File’.
• Use Step Over (F10), Step Into (F11), and Continue (F5) to navigate.
6. Install Packages Using pip
Example: Install the requests library:
python -m pip install requests
Sample usage:
import requests
resp = requests.get(‘https://httpbin.org/get’)
print(‘Status:’, resp.status_code)
print(‘JSON keys:’, list(resp.json().keys()))
7.Troubleshooting Tips
• If ‘python’ command is not recognized, ensure Python is added to PATH.
• Use ‘python3’ instead of ‘python’ on macOS/Linux.
• If pip is missing, reinstall Python or run ‘python -m ensurepip’.