explainx.ai0k
TrendingAI News TodayPathwaysSkills
Pricing
explainx.ai

Upskill in AI — 16 free pathways, live workshops & bootcamps, and 50+ courses from practitioners. Plus the skills, tools, and MCP servers to practice on.

follow us

follow on google

Add explainx.ai as a preferred source

corporate training

support@explainx.ai

get started

Find your pathTake Free Evaluation

community

Join the community

learn

mind: share how you thinkpathways — start freeworkshopsbootcampscoursescompare Explainxcertificationsmock testsexplainx universitycorporate traininglearn skills & mcp

discover

skillsmcp serversexplainx mcptoolsmdx readeragentsllmsdesignsdictionarypeopleagi trackerfelony benchranks

company

aboutvisionmissionteaminstructorsteach on explainxpartnershipscommunityhackathonscareers

content

daily AI newsstate of AI — live resultsblogreleasespromptsgeneratorsresource libraryfor LLMsexplainx.ai kids

solutions

all solutionsdeveloper upskillingmarketing upskillingproduct manager upskillingleadership upskilling

newsletter · weekly

Get AI news, tools, and insights in your inbox.

supportcontactprivacytermsdata rightshow we create contentsubmission guidelines

© 2026 AISOLO Technologies Pvt Ltd

explainx.ai

On this page

  • Step 1: Install Python
  • Step 2: Install a code editor
  • Step 3: Write and run your first script
  • The core concepts
  • Step 4: Set up a virtual environment
  • Step 5: Install packages with pip
  • Step 6: A real beginner project
  • Common beginner mistakes
  • Confirm installation before adding packages
  • Make sure the editor and terminal use the same Python
  • Turn the weather example into a learning exercise
  • Learn values by predicting the next line
  • A debugging routine you can repeat
  • What to learn next
← Back to blog

explainx / blog

Python Basics: How to Install Python and Write Your First Script (2026 Guide)

Python, Beginner Guide, Programming, Developer Tools, Setup Guide

Python explained from scratch: how to install it on Mac and Windows, how to write and run your first script, and the core concepts — variables, functions, loops, and pip — that you'll use in every Python project.

Jun 27, 2026·8 min read·Yash Thakker
add explainx.ai
go deep
Python Basics: How to Install Python and Write Your First Script (2026 Guide)

Python is the most-used programming language in AI, data science, and automation. It's also widely considered the easiest language to learn first — the syntax is close to plain English and the feedback loop is immediate.

This guide gets you from nothing to a working Python setup with a real script in under 30 minutes.

Install Python and write your first scripts — full beginner walkthrough.

Weekly digest3.5k readers

Catch up on AI

Curated AI updates on agents, skills, and MCP — delivered to your inbox. Unsubscribe anytime.

Step 1: Install Python

Python basics diagram showing a line of code coiling into a simple snake silhouette

macOS

Check if Python is already installed:

bash
python3 --version

If you see Python 3.10 or higher, you can skip to Step 2. If not, or if you want the latest version:

Option A — Homebrew (recommended):

bash
brew install python

If you don't have Homebrew, install it first:

bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Option B — Official installer:

  1. Go to python.org/downloads
  2. Download the current supported Python 3 macOS installer
  3. Run the .pkg file and follow the installer

After installation:

bash
python3 --version

You should see the Python 3 version you installed.

Windows

  1. Go to python.org/downloads
  2. Download the current supported Python 3 Windows installer
  3. Run the installer
  4. Important: Check the box that says "Add Python to PATH" before clicking Install

Open Command Prompt or PowerShell and verify:

bash
python --version

On Windows, the command is python (not python3). On Mac/Linux, use python3 to avoid accidentally using an old Python 2 installation.


Step 2: Install a code editor

If you haven't already, install Cursor or VS Code. Both have excellent Python support.

In VS Code or Cursor, install the Python extension by Microsoft — it adds syntax highlighting, autocomplete, and the ability to run Python files directly in the editor.


Step 3: Write and run your first script

Create a folder for your Python projects:

bash
mkdir python-projects
cd python-projects

Create your first Python file:

bash
# Mac/Linux
touch hello.py

# Windows
type nul > hello.py

Open hello.py in your editor and type:

python
print("Hello, Python!")

name = "Alice"
print(f"Hello, {name}!")

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"The sum of {numbers} is {total}")

Run it:

bash
# Mac/Linux
python3 hello.py

# Windows
python hello.py

Output:

snippet
Hello, Python!
Hello, Alice!
The sum of [1, 2, 3, 4, 5] is 15

The core concepts

Variables

Variables store values. No type declaration needed — Python figures it out:

python
name = "Alice"           # string
age = 28                 # integer
height = 5.7             # float
is_student = True        # boolean

print(name, age, height, is_student)

Strings and f-strings

python
first = "Alice"
last = "Smith"

# Concatenation (old way)
full = first + " " + last

# f-strings (modern way — preferred)
full = f"{first} {last}"
greeting = f"Hello, {first}! You are {age} years old."

print(greeting)

Lists

python
fruits = ["apple", "banana", "cherry"]

print(fruits[0])         # apple — indexing starts at 0
print(fruits[-1])        # cherry — last item

fruits.append("mango")   # add to end
fruits.remove("banana")  # remove by value

print(len(fruits))       # 3 — number of items

Dictionaries

python
person = {
    "name": "Alice",
    "age": 28,
    "city": "London"
}

print(person["name"])    # Alice
person["job"] = "Engineer"  # add a new key
print(person)

If / else

python
age = 20

if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

For loops

python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I like {fruit}")

# Loop over a range of numbers
for i in range(5):
    print(i)   # prints 0, 1, 2, 3, 4

# Loop with index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Functions

python
def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

message = greet("Alice")
print(message)

result = add(3, 4)
print(result)    # 7

Functions with default parameters:

python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))           # Hello, Alice!
print(greet("Bob", "Hi"))       # Hi, Bob!

Step 4: Set up a virtual environment

A virtual environment isolates your project's packages from the rest of your system. Always use one.

Create a virtual environment in your project folder:

bash
# Mac/Linux
python3 -m venv venv

# Windows
python -m venv venv

Activate it:

bash
# Mac/Linux
source venv/bin/activate

# Windows (Command Prompt)
venv\Scripts\activate.bat

# Windows (PowerShell)
venv\Scripts\Activate.ps1

When activated, your terminal prompt shows (venv) at the start:

snippet
(venv) user@machine:~/python-projects$

Everything you install now goes into this environment, not your system Python.

To deactivate when you're done:

bash
deactivate

Step 5: Install packages with pip

pip is Python's package installer. With your virtual environment active:

bash
pip install requests

This installs the requests library — the standard way to make HTTP calls in Python.

Test it:

python
import requests

response = requests.get("https://api.github.com")
print(response.status_code)   # 200
print(response.json()["current_user_url"])

Save your dependencies so others can replicate your environment:

bash
pip freeze > requirements.txt

To install from a requirements.txt on a new machine:

bash
pip install -r requirements.txt

Step 6: A real beginner project

Build a script that fetches today's weather for any city using a free API.

Install the requests library if you haven't:

bash
pip install requests

Create weather.py:

python
import requests

def get_weather(city):
    url = f"https://wttr.in/{city}?format=j1"
    response = requests.get(url)
    
    if response.status_code != 200:
        return f"Could not fetch weather for {city}"
    
    data = response.json()
    current = data["current_condition"][0]
    
    temp_c = current["temp_C"]
    feels_like = current["FeelsLikeC"]
    description = current["weatherDesc"][0]["value"]
    
    return f"{city}: {description}, {temp_c}°C (feels like {feels_like}°C)"

cities = ["London", "New York", "Tokyo", "Mumbai"]

for city in cities:
    print(get_weather(city))

Run it:

bash
python3 weather.py

You're fetching live data, parsing JSON, and printing formatted output — with less than 25 lines of code.


Common beginner mistakes

Not activating the virtual environment. If you install packages and they "don't work", check that (venv) is showing in your terminal prompt.

Using python vs python3. On Mac/Linux, always use python3. On Windows, python usually points to Python 3 if you installed it correctly.

Indentation errors. Python uses indentation (spaces) instead of curly braces to structure code. Mixing tabs and spaces causes errors. Use spaces consistently (4 spaces per indent is the standard).

Forgetting to save the file. Python runs whatever is on disk, not what's in your editor. Save before running.


Confirm installation before adding packages

Choose a supported Python 3 release using the official downloads page rather than treating the tutorial's example version as the newest release. The examples teach ordinary Python 3 syntax and do not require a particular patch version. If your project specifies a runtime, follow that requirement.

Run the version check in a newly opened terminal after installation. An already open shell or editor may still have its previous environment. Record the reported version and interpreter location with your project notes. When sharing a setup problem, those two facts help another person distinguish a missing installation from a command pointing at the wrong executable.

Make sure the editor and terminal use the same Python

A Python installation is a program on disk, and a virtual environment points at a particular installation. You can have several interpreters without anything being broken. Trouble starts when your editor runs one interpreter while your terminal installs packages into another. Before changing settings at random, find out which interpreter each tool actually uses.

Inside your activated environment, run the following diagnostic. It prints the interpreter location, then asks that same interpreter to locate pip. The output paths should refer to your project environment rather than an unrelated system folder.

bash
python -c "import sys; print(sys.executable)"
python -m pip --version

Prefer installing with Python's module form rather than a bare pip command. This makes the relationship explicit: the Python you just selected receives the package. In your editor, use its interpreter selector to choose the environment created for this folder. If a library imports successfully in the terminal but the editor underlines it, check that selection before reinstalling everything.

The official virtual-environment tutorial explains how activation changes the interpreter selected by the shell. Activation lasts for that shell session. Opening a new terminal tab may require activation again; it does not mean yesterday's packages disappeared. Keep your source files outside the environment folder so you can recreate the environment without losing your project.

Turn the weather example into a learning exercise

The weather script is intentionally small. Treat its network response as input you do not control. A service can be unavailable, return an error page, or change a field. A working request today does not establish that every future request will succeed. Separate three questions: did the connection finish, was the response successful, and did the response contain the structure your code expected?

Add a timeout to the request so the script does not wait indefinitely. Handle a request failure with a message naming the city. Then handle malformed data separately; this makes it clear whether the problem came from connectivity or your assumptions about the response. Avoid a broad exception handler that turns every programming mistake into an apparently successful weather report.

python
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()

This fragment belongs inside your existing function, with appropriate exception handling around the request. It is not a complete replacement for the function. Python's errors and exceptions tutorial distinguishes invalid syntax from failures during execution and shows how specific exception types are handled.

Now add a user-entered city. First print the input without making a network call. Next pass it to your function. Finally try an empty string, a city with spaces, and a deliberately invalid city name. Write down what the program should do for each case before running it. That small habit turns debugging into comparing observed behavior with an explicit expectation.

Learn values by predicting the next line

The fastest way to understand a variable is to predict how its value changes. Take the fruits list above, print it, append one item, and print it again. Ask why the second print has more items even though the variable name stayed the same. Then assign a new list to another variable and confirm that changing the original does not automatically add an item to this new list.

For functions, distinguish printing from returning. A print statement displays text for the person running the program. A return statement supplies a value to the caller so another calculation can use it. If your function prints a total but another function needs that total, return the number and leave presentation to the calling code. This keeps calculations reusable when your script eventually becomes a web service or notebook.

Try a spending tracker as an offline exercise. Start with three expenses, calculate their sum, and display the largest expense. Move the calculation into a function. Add an empty-list case before adding file storage. There is no API, authentication, or cloud service to distract you; every change teaches a Python concept you can see immediately.

A debugging routine you can repeat

When a script fails, save the file and rerun it once to confirm you are looking at the current version. Read the exception name and the last relevant line of the traceback. Find the referenced source line, then inspect the values it used. A missing variable, an unexpected string where you wanted a number, and a missing dictionary key require different fixes even when they all stop the script.

Reduce the problem rather than rewriting the project. If a loop fails on the fourth city, run the function with only that city. If an import fails, create a tiny file containing just the import and interpreter diagnostic. Keep your last working version nearby so you can compare the smallest difference that introduced the problem.

Before adding an AI SDK, make sure you can run your own file, activate its environment, install one package into that environment, and explain a simple traceback. Those skills remain useful regardless of which library or model you choose. The goal of this first project is understanding the path from source code to execution, not collecting installations you cannot troubleshoot.

What to learn next

  • File I/O — reading and writing files with open()
  • Error handling — try / except blocks
  • List comprehensions — [x * 2 for x in numbers] — a concise way to build lists
  • Classes — object-oriented programming with class
  • Common libraries — pandas for data, flask for web APIs, anthropic for Claude AI

The Anthropic Python SDK lets you call Claude from a Python script:

bash
pip install anthropic
python
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain Python decorators simply."}]
)

print(message.content[0].text)

Python is the language most AI and ML work is written in — now you have the foundation to explore it.

Spotted something out of date? Let us know.
Yash Thakker

Written by

Yash Thakker

Yash is an AI expert with over 300K learners. Join his workshops →

View Yash Thakker in People in AI →

Related posts

Sep 11, 2026

How AI Agents Actually Edit Code Using Python

When a coding agent "edits your code," it's almost always generating a text diff and hoping it applies cleanly — not understanding the code's structure. Python has a mature toolkit (ast, libcst, rope, tree-sitter) for structural, syntax-aware editing instead, and understanding the difference explains why some agent edits break and others don't.

Aug 10, 2026

DHH: Fable One-Shotted a Rust Rewrite in 11M Tokens

On August 10, 2026, Ruby on Rails creator DHH posted that Fable one-shotted a full Rust port of the Python library TerminalTextEffects in 11 million tokens — cutting startup from 87ms to 2ms and boosting rendering speed 9.6x. explainx.ai breaks down what "one-shot" means here, why the performance gap is mostly about Python's interpreter, not clever Rust, and why replies calling this the easy case for AI rewrites have a point.

Jun 27, 2026

What is Cursor? How to Build Your First HTML Project with AI (2026 Guide)

Cursor explained from scratch: how to install it, how the AI works, and how to build a real HTML page from a plain-English description. Your first AI-assisted project in under 30 minutes.