Python Crash Course for AI

Duration: 45 min

Python Crash Course for AI

Duration: 45 min

This course covers Python fundamentals needed for AI development. For a complete, hands-on Python course with exercises and projects, take our dedicated course:

[→ Python Fundamentals Course](https://ailearningclub.com/course-md.html?id=python-fundamentals)

Covers:

  • Variables, types, and operations
  • Lists, dictionaries, and data structures
  • Functions and modules
  • Working with NumPy and Pandas
  • Real-world exercises and projects

Recommendation: Complete the Python Fundamentals course before proceeding with Advanced ML topics. You'll need strong Python fundamentals to build and deploy models effectively.

Dictionaries (Key-Value Pairs)

Perfect for structured data

model_config = { "algorithm": "random_forest", "n_estimators": 100, "max_depth": 10, "accuracy": 0.94 }

Access

print(model_config["algorithm"]) # "random_forest" print(model_config.get("missing", 0)) # 0 (safe access)

Add/update

model_config["trained"] = True

Loops

For loop: iterate over a sequence

datasets = ["train.csv", "test.csv", "validation.csv"] for name in datasets: print(f"Loading {name}...")

Range: repeat N times

for epoch in range(5): print(f"Training epoch {epoch + 1}/5")

Enumerate: get index + value

results = [0.85, 0.89, 0.92, 0.91] for i, acc in enumerate(results): print(f"Epoch {i+1}: accuracy = {acc:.2%}")

Functions

def evaluate_model(y_true, y_pred):
    """Calculate accuracy of predictions."""
    correct = sum(1 for t, p in zip(y_true, y_pred) if t == p)
    accuracy = correct / len(y_true)
    return accuracy

Use it

true_labels = [1, 0, 1, 1, 0] predictions = [1, 0, 0, 1, 0] acc = evaluate_model(true_labels, predictions) print(f"Accuracy: {acc:.1%}") # 80.0%

List Comprehensions (Pythonic!)

Transform data in one line

numbers = [1, 2, 3, 4, 5] squared = [x2 for x in numbers] # [1, 4, 9, 16, 25] evens = [x for x in numbers if x % 2 == 0] # [2, 4]

Real ML example: normalize features

raw = [100, 200, 150, 300, 250] min_val, max_val = min(raw), max(raw) normalized = [(x - min_val) / (max_val - min_val) for x in raw]

[0.0, 0.5, 0.25, 1.0, 0.75]

Imports

Import a module

import numpy as np import pandas as pd

Import specific functions

from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score

The pattern you'll use 100 times:

import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split

Putting It Together

A complete mini-program

def load_and_split(filepath, test_size=0.2): """Load CSV data and split into train/test.""" import pandas as pd from sklearn.model_selection import train_test_split df = pd.read_csv(filepath) X = df.drop("target", axis=1) y = df["target"] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_size, random_state=42 ) print(f"Loaded {len(df)} rows") print(f"Train: {len(X_train)}, Test: {len(X_test)}") return X_train, X_test, y_train, y_test

Quiz

Q1: What does scores[-1] return for scores = [10, 20, 30]?

  • A) 10
  • B) 20
  • C) 30 ✓
  • D) Error

Q2: What does [x*2 for x in [1,2,3]] produce?

  • A) [1, 2, 3]
  • B) [2, 4, 6]
  • C) [1, 4, 9]
  • D) 6

Q3: What's the standard alias for importing numpy?

  • A) import numpy as numpy
  • B) import numpy as np
  • C) from numpy import *
  • D) import np