Fundamentals
In this lesson, I’ll show you the basics of using Python and introduce some things that you can do with the standard library, like working with datetime objects and JSON files.
Python has been widely adopted in the data community because:
- High-Level Language Benefits: Python abstracts away low-level details like memory management, allowing developers to focus on problem-solving rather than hardware complexities.
- Syntax and Design Choices: The syntax is very clean, making it easy to read. Python’s design philosophy emphasizes readability with its use of significant whitespace, clear keywords, and minimal use of special characters. The language follows the “There should be one—and preferably only one—obvious way to do it” principle, reducing confusion and promoting consistent code patterns.
- Extensive Libraries for Data: Tools like NumPy, Pandas, and TensorFlow provide powerful capabilities for data manipulation, numerical computations, and building AI models. These libraries expose Python interfaces to optimized compiled operations, with implementations in languages such as C and C++. NumPy’s homogeneous arrays and compiled numerical routines support efficient computation in memory.
This Lesson Will Cover
- 🛠️ Setting up a Python environment
- 🐍 Essential Python syntax
- 📦 Variables and data types
- 🔄 Control flow (conditionals and loops)
- 🏗️ Functions
- 📂 File operations
- 📚 The Python standard library (
datetime,json,regex,os)
Setting up a Python Environment
To get started with Python development, you’ll want to set up a Jupyter Notebook environment. I recommend this for any Python developer (not just data people like us) because it’s the perfect environment for experimenting with the language and learning how it works.
-
Install Python
- Download and install Python
- Verify installation by opening a terminal and running:
python --version- Ensure this is Python 3
-
Install VS Code
- Download and install VS Code
- Install the Python extension from Microsoft
- Install the Jupyter extension for notebook support
-
Create a Virtual Environment
# Create a new virtual environment (here I named id adhoc-venv) python -m venv adhoc-venv # Activate it (Mac/Linux) source adhoc-venv/bin/activate # Activate it (Windows) adhoc-venv\Scripts\activate -
Install Essential Packages
# After activating your virtual environment pip install numpy pandas matplotlib scikit-learn -
Open a Jupyter Notebook in VS Code
# Navigate to your project directory cd my-project # Open VS Code code . # Launch a Jupyter Notebook # 1. Create a new .ipynb file # 2. Select the Python virtual environment you just setup # 3. Start coding in notebook cells
If everything went well, you’re now ready to start coding.
Note:
- You can use any IDE you want.
- You can install and use the Jupyter Notebook (
jupyter notebook) or Jupyter Lab (jupyter lab). - You can use the Anaconda Python distribution and conda to manage environments.
There is no “right way.” Just do whatever works for now—you can always change things later.
Essential Python Syntax
Variables and Data Types
Python is not statically typed. We can define variables without explicitly declaring their type and then change them later.
# Define variables
jobs = "AI Engineer, Dad" # String
age = 35 # Integer
accuracy = 89.8 # Float
is_successful = True # Boolean
# Change data types
jobs = ["AI Engineer", "Dad"]
is_successful = "sometimes"
print(f"Jobs: {jobs}, Age: {age}, Accuracy: {accuracy}, Successful: {is_successful}")
# Output:
# Jobs: ['AI Engineer', 'Dad'], Age: 35, Accuracy: 89.8, Successful: sometimes
Key data types include:
- Integers: Whole numbers (
int) - Floating-point numbers: Decimal values (
float) - Strings: Text (
str) - Booleans: True/False values (
bool)
Data Structures: Lists, Dictionaries, and Sets
These are the basic data structures in Python:
Lists: Ordered collections.
# Example of a list
models = ["Linear Regression", "Decision Tree", "Neural Network"]
print(models[0]) # Access first item
# Output: Linear Regression
Dictionaries: Key-value pairs.
# Example of a dictionary
model_metrics = {"accuracy": 0.95, "precision": 0.89}
print(model_metrics["accuracy"]) # Access value by key
# Output:
# 0.95
Sets: Unordered collections of unique items.
# Example of a set
unique_labels = {"cat", "dog", "mouse", "cat"}
print("dog" in unique_labels)
# Output:
# True
Control Flow
Python’s control flow may as well be pseudocode (the syntax is very simple):
Conditionals:
accuracy = 0.87
if accuracy > 0.9:
print("High accuracy!")
elif accuracy > 0.8:
print("Moderate accuracy.")
else:
print("Needs improvement.")
# Output:
# Moderate accuracy.
Loops:
# Looping through a list
for model in models:
print(f"Training: {model}")
# Output:
# Training: Linear Regression
# Training: Decision Tree
# Training: Neural Network
We can also loop through dictionaries with style:
# Loop through keys
for key in model_metrics.keys():
print(f"Metric: {key}")
# Loop through values
for value in model_metrics.values():
print(f"Score: {value}")
# Loop through key-value pairs
for key, value in model_metrics.items():
print(f"{key}: {value}")
# Output:
# Metric: accuracy
# Metric: precision
# Score: 0.95
# Score: 0.89
# accuracy: 0.95
# precision: 0.89
Functions
Functions are used to organize code into reusable blocks that perform specific tasks:
# Define a function to calculate accuracy
def calculate_accuracy(true_positives, total):
if total <= 0:
raise ValueError(f"Invalid total: {total}")
accuracy = true_positives / total
return accuracy
accuracy = calculate_accuracy(87, 100)
print(f"Model accuracy: {accuracy}")
# Output:
# Model accuracy: 0.87
File Operations
# Writing text files
with open("output.txt", "w") as f:
f.write("Model training completed\n")
f.write(f"Accuracy: {0.95}")
# Reading text files
with open("output.txt", "r") as f:
content = f.read()
lines = content.split("\n")
print(lines)
# Output:
# ['Model training completed', 'Accuracy: 0.95']
Standard Library
As promised, here are some examples of using functions in the standard library.
Working with Dates and Times
from datetime import datetime, timedelta
# Create dates
now = datetime.now()
specific_date = datetime(2023, 12, 25, 10, 30)
# Date arithmetic
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
# Format dates
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date, type(formatted_date))
# Output: 2024-12-02 09:41:24 <class 'str'>
# Parse dates
date_string = "2023-12-25 10:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date, type(parsed_date))
# Output:
# 2025-02-25 15:23:04 <class 'str'>
# 2023-12-25 10:30:00 <class 'datetime.datetime'>
JSON Data Handling
import json
# Sample data
data = {
"model": "neural_network",
"parameters": {
"layers": [64, 32, 16],
"activation": "relu"
},
"metrics": [0.95, 0.92, 0.94]
}
# Write JSON to file
with open("model_config.json", "w") as f:
json.dump(data, f, indent=4)
# Read JSON from file
with open("model_config.json", "r") as f:
loaded_data = json.load(f)
print(loaded_data)
# Output:
# {'model': 'neural_network', 'parameters': {'layers': [64, 32, 16], 'activation': 'relu'}, 'metrics': [0.95, 0.92, 0.94]}
Regular Expressions
import re
# Find all dates in text
text = "Training started on 2023-01-15, and ended on 2023-02-28!"
dates = re.findall(r"\d{4}-\d{2}-\d{2}", text)
print(dates)
# Replace patterns
cleaned_text = re.sub(r"[^\w\s-]", "", text) # Remove punctuation
print(cleaned_text)
# Output:
# ['2023-01-15', '2023-02-28']
# Training started on 2023-01-15 and ended on 2023-02-28
System and Path Operations
from pathlib import Path
# Working with paths
current_dir = Path.cwd()
file_path = current_dir / "data" / "dataset.csv"
# Create directories
data_dir = Path("data/processed")
data_dir.mkdir(parents=True, exist_ok=True)
# Create some sample files
(data_dir / "file1.txt").write_text("This is file 1")
(data_dir / "file2.csv").write_text("id,value\n1,100\n2,200")
(data_dir / "file3.csv").write_text("name,score\nAlice,95\nBob,87")
# List files
files = list(Path("data").iterdir())
csv_files = list(Path("data").glob("*.csv"))
# Check file existence and print contents
if file_path.exists():
print(f"Found file: {file_path}")
print("\nListing all files in data/processed:")
for file in data_dir.iterdir():
print(f"\nContents of {file.name}:")
print(file.read_text())
# Output:
# Listing all files in data/processed:
#
# Contents of file1.txt:
# This is file 1
#
# Contents of file2.csv:
# id,value
# 1,100
# 2,200
#
# Contents of file3.csv:
# name,score
# Alice,95
# Bob,87
Conclusion
And that’s the basics of Python! It really is a beautiful, minimal language. It’s great for beginners who are learning to code, but it also goes really deep - making it great for professionals and production use cases as well.
Key Takeaways
🐍 Python is versatile and easy to read.
📓 Jupyter Notebooks are excellent for interactive development.
📂 Essential Python structures: lists, dictionaries, and sets.
🛠️ The standard library provides powerful tools for handling files, dates, and JSON.
Next: Key Data Libraries: NumPy, Pandas, Matplotlib
The Python standard library is relatively extensive, but it will only get us so far.
In the next lesson, we’ll learn the cornerstone libraries for working with data.
Comments (0)
No comments yet.