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.
Step 1: Install Python

macOS
Check if Python is already installed:
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):
brew install python
If you don't have Homebrew, install it first:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Option B — Official installer:
- Go to python.org/downloads
- Download the current supported Python 3 macOS installer
- Run the
.pkgfile and follow the installer
After installation:
python3 --version
You should see the Python 3 version you installed.
Windows
- Go to python.org/downloads
- Download the current supported Python 3 Windows installer
- Run the installer
- Important: Check the box that says "Add Python to PATH" before clicking Install
Open Command Prompt or PowerShell and verify:
python --version
On Windows, the command is
python(notpython3). On Mac/Linux, usepython3to 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:
mkdir python-projects
cd python-projects
Create your first Python file:
# Mac/Linux
touch hello.py
# Windows
type nul > hello.py
Open hello.py in your editor and type:
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:
# Mac/Linux
python3 hello.py
# Windows
python hello.py
Output:
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:
name = "Alice" # string
age = 28 # integer
height = 5.7 # float
is_student = True # boolean
print(name, age, height, is_student)
Strings and f-strings
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
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
person = {
"name": "Alice",
"age": 28,
"city": "London"
}
print(person["name"]) # Alice
person["job"] = "Engineer" # add a new key
print(person)
If / else
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
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
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:
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:
# Mac/Linux
python3 -m venv venv
# Windows
python -m venv venv
Activate it:
# 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:
(venv) user@machine:~/python-projects$
Everything you install now goes into this environment, not your system Python.
To deactivate when you're done:
deactivate
Step 5: Install packages with pip
pip is Python's package installer. With your virtual environment active:
pip install requests
This installs the requests library — the standard way to make HTTP calls in Python.
Test it:
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:
pip freeze > requirements.txt
To install from a requirements.txt on a new machine:
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:
pip install requests
Create weather.py:
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:
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.
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.
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 / exceptblocks - List comprehensions —
[x * 2 for x in numbers]— a concise way to build lists - Classes — object-oriented programming with
class - Common libraries —
pandasfor data,flaskfor web APIs,anthropicfor Claude AI
The Anthropic Python SDK lets you call Claude from a Python script:
pip install anthropic
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.
