This is a practical Python reference for beginners. It starts with installation and moves through core syntax, data analysis, machine learning, deep learning and AI. Work through the sections in order, type the examples yourself and change the values so you can see how the code behaves.
Beginner to intermediateAbout 18 minutesLast updated August 2026
A note from the author
I’m Imonikhe Ayeni. I use Python in data analysis, research and reporting work.
I put this reference together so learners can find the main ideas and examples in one place.
No matching sections were found. Try a broader search term.
01
Installing Python and setting up your workspace
Install a current Python 3 release from the official Python website. The exact version
number changes over time, so choose the latest stable release that is compatible with
the packages you plan to use. After installation, confirm that Python and pip work
before installing data-science packages.
Windows installation
1. Visit the official Python downloads page.
2. Download the current Python 3 installer for Windows.
3. Open the installer.
4. Select “Add python.exe to PATH” before continuing.
5. Choose “Install Now”.
6. Open Command Prompt or PowerShell after installation.
7. Run the verification commands below.
Optional:
Install Visual Studio Code and add the official Python extension.
Recommended beginner route:
1. Visit the official Python downloads page.
2. Download the signed macOS installer.
3. Open the downloaded .pkg file.
4. Follow the installation wizard.
5. Open Terminal.
6. Verify the installation with python3 and pip3.
Do not rely on an older system-provided Python installation for your projects.
mkdir python-learning
cd python-learning
# Windows
py -m venv .venv
.venv\Scripts\activate
# macOS or Linux
python3 -m venv .venv
source .venv/bin/activate
# Leave the environment later
deactivate
import sys
import numpy as np
import pandas as pd
import sklearn
print("Python:", sys.version)
print("NumPy:", np.__version__)
print("pandas:", pd.__version__)
print("scikit-learn:", sklearn.__version__)
print("Your Python data-science environment is ready.")
02
Python fundamentals
Variables store information. Python determines the data type automatically. Common types include integers, decimal numbers, strings, Boolean values and None.
Variables and data types
name = "Imonikhe" # string
age = 38 # integer
height = 1.78 # float
is_learning = True # Boolean
result = None # no value yet
print(type(name))
print(f"{name} is {age} years old.")
Arithmetic and comparisons
a = 10
b = 3
print(a + b) # addition
print(a - b) # subtraction
print(a * b) # multiplication
print(a / b) # division
print(a // b) # whole-number division
print(a % b) # remainder
print(a ** b) # power
print(a > b)
print(a == 10)
print(a != b)
Strings
message = " Python for Data Science "
print(message.strip())
print(message.lower())
print(message.upper())
print(message.replace("Python", "AI"))
print(message.split())
print("Data" in message)
03
Lists, tuples, dictionaries and sets
Collections allow you to store multiple values. Lists are changeable, tuples are normally fixed, dictionaries store key-value pairs, and sets keep unique values.
scores = [70, 80, 90]
for score in scores:
print(score)
for index, score in enumerate(scores):
print(index, score)
for number in range(1, 6):
print(number)
While, break and continue
count = 1
while count <= 5:
if count == 3:
count += 1
continue
print(count)
if count == 4:
break
count += 1
List comprehensions
squares = [number ** 2 for number in range(1, 6)]
even_numbers = [number for number in range(10) if number % 2 == 0]
scores = [45, 67, 82, 39, 91]
passed = [score for score in scores if score >= 50]
05
Functions and error handling
Functions package reusable logic. Parameters provide inputs, and return sends a result back. Error handling keeps programs from failing without explanation.
Reusable functions
def calculate_mean(values: list[float]) -> float:
if not values:
raise ValueError("The list cannot be empty.")
return sum(values) / len(values)
scores = [70, 80, 90]
average = calculate_mean(scores)
print(average)
try:
number = int("hello")
except ValueError as error:
print(f"Conversion failed: {error}")
finally:
print("Operation finished.")
06
Files and object-oriented basics
The with statement safely opens and closes files. Classes are templates for creating objects and are widely used by machine-learning libraries.
Reading and writing text
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
with open("output.txt", "w", encoding="utf-8") as file:
file.write("Python is useful for data science.")
A simple class
class MachineLearningModel:
def __init__(self, name: str, accuracy: float):
self.name = name
self.accuracy = accuracy
def display_result(self) -> None:
print(f"{self.name}: {self.accuracy:.2%}")
model = MachineLearningModel("Random Forest", 0.91)
model.display_result()
07
NumPy for numerical computing
NumPy provides efficient arrays, matrices, vectorised calculations and statistical functions. Vectorised operations are normally faster and cleaner than manual loops.
Real-world data may contain missing values, duplicates, inconsistent types and badly formatted dates. Investigate the cause before deleting or replacing information.
split_position = int(len(df) * 0.8)
train = df.iloc[:split_position]
test = df.iloc[split_position:]
# Do not randomly shuffle observations when future values
# must be predicted from earlier values.
12
Data visualisation
Charts help reveal patterns, trends, distributions and unusual observations. Always label axes and provide a meaningful title.
SciPy contains common statistical tests. A p-value does not measure the size or importance of an effect, so report effect sizes and confidence intervals where possible.
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
knn_model = KNeighborsClassifier(n_neighbors=5)
svm_model = SVC(kernel="rbf", probability=True, random_state=42)
16
Preprocessing and pipelines
Pipelines apply the same preprocessing consistently during training, testing and later prediction. They also reduce the risk of data leakage.
Scaling
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Fit on training data only.
# Never fit the scaler separately on the test data.
Evaluation must match the problem. Accuracy can be misleading when classes are imbalanced. Precision, recall, F1-score, ROC-AUC and the confusion matrix provide additional information.
Cross-validation
from sklearn.model_selection import cross_val_score
scores = cross_val_score(
model,
X,
y,
cv=5,
scoring="roc_auc"
)
print(scores)
print(scores.mean())
print(scores.std())
Convolutional neural networks are widely used for images. LSTM and GRU networks are designed for sequences such as text, sensor readings and time-series data.
PyTorch uses tensors and explicit training loops. The standard sequence is: predict, calculate loss, clear gradients, backpropagate and update parameters.
Define and train a neural network
import torch
import torch.nn as nn
features = torch.tensor(
[[1.0, 2.0], [3.0, 4.0]]
)
targets = torch.tensor(
[[0.0], [1.0]]
)
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(
nn.Linear(2, 16),
nn.ReLU(),
nn.Linear(16, 1),
nn.Sigmoid()
)
def forward(self, inputs):
return self.network(inputs)
model = NeuralNetwork()
loss_function = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for epoch in range(100):
predictions = model(features)
loss = loss_function(predictions, targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print(epoch, loss.item())
22
Natural language processing
Text must be converted into numbers before a traditional machine-learning model can use it. TF-IDF is a strong baseline for many text-classification problems.
Simple text cleaning
text = "Python is GREAT for AI!"
clean_text = (
text.lower()
.replace("!", "")
.strip()
)
words = clean_text.split()
print(words)
TF-IDF text classifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
text_model = Pipeline([
("tfidf", TfidfVectorizer(stop_words="english")),
("classifier", LogisticRegression(max_iter=1000))
])
text_model.fit(training_texts, training_labels)
prediction = text_model.predict([
"The service was excellent."
])
print(prediction)
Pretrained transformer pipeline
from transformers import pipeline
sentiment_model = pipeline("sentiment-analysis")
result = sentiment_model(
"The service was excellent."
)
print(result)
23
Embeddings, semantic search and generative AI
Embeddings represent text as numerical vectors. Similar meanings tend to have nearby vectors, which enables semantic search and retrieval-augmented generation.
Create embeddings
from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer(
"all-MiniLM-L6-v2"
)
sentences = [
"Python is used for data science.",
"Machine-learning models learn from data."
]
embeddings = embedding_model.encode(sentences)
print(embeddings.shape)
Semantic search
from sklearn.metrics.pairwise import cosine_similarity
documents = [
"Python is a programming language.",
"SQL is used to query databases.",
"Machine-learning models learn patterns from data."
]
document_embeddings = embedding_model.encode(documents)
question = "How do computers learn from information?"
question_embedding = embedding_model.encode([question])
similarities = cosine_similarity(
question_embedding,
document_embeddings
)[0]
best_index = similarities.argmax()
print(documents[best_index])
Typical RAG flow
Documents
↓
Split into chunks
↓
Create embeddings
↓
Store vectors
↓
Retrieve relevant chunks
↓
Send context and question to a language model
↓
Generate a grounded answer
24
Saving and reusing models
Save the complete preprocessing-and-model pipeline whenever possible. This helps ensure that future data receives exactly the same transformations.
df.to_csv("cleaned_data.csv", index=False)
df.to_excel("cleaned_data.xlsx", index=False)
with pd.ExcelWriter("analysis_output.xlsx") as writer:
df.to_excel(writer, sheet_name="Clean Data", index=False)
summary.to_excel(writer, sheet_name="Summary", index=False)
25
Complete machine-learning template
This example combines missing-value handling, scaling, categorical encoding and logistic regression in one reusable pipeline.
End-to-end classification project
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.read_csv("patient_data.csv")
numeric_features = [
"age",
"blood_pressure",
"cholesterol"
]
categorical_features = [
"gender",
"smoking_status"
]
features = numeric_features + categorical_features
X = df[features]
y = df["has_disease"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore"))
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, numeric_features),
("categorical", categorical_pipeline, categorical_features)
])
model = Pipeline([
("preprocessor", preprocessor),
("classifier", LogisticRegression(
max_iter=1000,
class_weight="balanced"
))
])
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(classification_report(y_test, predictions))
joblib.dump(model, "patient_risk_model.joblib")
26
Good coding habits and common mistakes
Readable, reproducible code is easier to test, maintain and share. Use descriptive names, small functions, fixed random seeds and explicit validation.
Good habits
RANDOM_STATE = 42
TEST_SIZE = 0.2
analysis_data = df.copy()
if "target" not in analysis_data.columns:
raise ValueError("The target column is missing.")
print(analysis_data.shape)
print(analysis_data.head())
print(analysis_data.isna().sum())
Avoid data leakage
# Incorrect: learns from all data before splitting.
scaler.fit(X)
# Correct: fit only on the training data.
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
Remember the basics
• Use = for assignment and == for comparison.
• Place a colon after if, elif, else, for, while, def and class.
• Python is case-sensitive: score and Score are different names.
• Put pandas conditions in parentheses and use & or |.
• Read error messages from the final line upward.
• Test code on a small sample before running it on a large dataset.
27
Four-week learning plan
Progress comes from writing and debugging code, not only reading it. Re-type the examples, change the inputs, deliberately create errors and explain the output in your own words.
Week 1 — Python foundations
Variables, data types, collections, conditions, loops, functions, files and exceptions.
Practice projects:
• Calculator
• Grade classifier
• Expense tracker
• Simple patient-record program
Week 2 — Data analysis
NumPy, pandas, missing values, grouping, merging, dates, visualisation and basic statistics.
Practice project:
• Exploratory analysis of a public health, NHS, sales or survey dataset
Week 3 — Machine learning
Regression, classification, preprocessing, pipelines, evaluation, cross-validation and tuning.
Practice projects:
• One regression project
• One classification project
Week 4 — Deep learning and AI
Neural networks, TensorFlow or PyTorch, NLP, transformers, embeddings and semantic search.
Practice project:
• Text classifier or document-question-answering prototype