🐍 Prerequisite • Programming

Python Basics for AI

Python is the language of AI. Understanding variables, data types, and basic operations is the foundation for reading and writing machine learning code. This guide teaches you the essentials—no prior programming experience required.

Estimated reading time: 20-25 minutes

🎯 What You'll Learn

  • How to create and use variables to store data
  • Python's core data types: numbers, strings, and booleans
  • Arithmetic, comparison, and logical operators
  • How to format and print output
  • Type conversion and common operations

1 Why Python for AI?

Python has become the dominant language in AI and machine learning for several reasons:

  • Readability: Python code looks almost like English, making it easy to learn and understand
  • Rich Ecosystem: Libraries like NumPy, PyTorch, and TensorFlow make AI development efficient
  • Community: Massive community means tutorials, answers, and pre-built solutions for everything
  • Flexibility: Quick prototyping and experimentation

🤖 The AI Connection

Almost all AI research papers include Python code. PyTorch, TensorFlow, Hugging Face, LangChain—the tools you'll use to build AI applications are all Python-first. Even if you primarily understand concepts, reading Python helps you understand implementations.

Python
# A simple AI example: loading and using a model
from transformers import pipeline

# Create a sentiment analysis pipeline
classifier = pipeline("sentiment-analysis")

# Use it!
result = classifier("Python makes AI accessible!")
print(result)  # [{'label': 'POSITIVE', 'score': 0.9998}]

Don't worry if this looks complex now—by the end of these prerequisites, you'll understand every line.

2 Variables: Storing Data

A variable is a name that refers to a value. Think of it as a labeled box that holds data. You create a variable by assigning a value to a name.

Python
# Creating variables
learning_rate = 0.001
epochs = 100
model_name = "gpt-4"
is_training = True

# Using variables
print(learning_rate)     # 0.001
print(model_name)        # gpt-4

Variable Naming Rules

  • Must start with a letter or underscore (_)
  • Can contain letters, numbers, and underscores
  • Case-sensitive: Model and model are different
  • Cannot use Python keywords (if, for, class, etc.)
✓ Good Names
learning_rate = 0.01
batch_size = 32
num_epochs = 10
model_v2 = "improved"
_hidden = 768
✗ Invalid Names
# 2nd_model = "x"  # Can't start with number
# learning-rate = 0.01  # No hyphens
# class = "A"  # 'class' is a keyword
# my variable = 5  # No spaces

💡 Python Convention

Use snake_case for variable names (words separated by underscores). This is the standard style in Python and makes code more readable: learning_rate, batch_size, num_layers.

Reassigning Variables

Variables can be changed (reassigned) at any time:

Python
accuracy = 0.75
print(accuracy)  # 0.75

accuracy = 0.92  # Reassign to new value
print(accuracy)  # 0.92

# Even change type (dynamic typing)
accuracy = "high"
print(accuracy)  # high

3 Data Types

Every value in Python has a type that determines what operations you can perform on it. Python is "dynamically typed"—you don't declare types explicitly.

Type Description Examples
int Whole numbers 42, -7, 0, 1000000
float Decimal numbers 3.14, -0.001, 2.0, 1e-5
str Text (strings) "hello", 'AI', "123"
bool True or False True, False
None No value / null None

Numbers: int and float

Python
# Integers (whole numbers)
batch_size = 32
num_layers = 12
vocab_size = 50000

# Floats (decimals)
learning_rate = 0.001
accuracy = 0.9543
loss = 2.3e-4  # Scientific notation: 0.00023

# Check the type
print(type(batch_size))    # <class 'int'>
print(type(learning_rate)) # <class 'float'>

Strings: Text Data

Python
# Strings can use single or double quotes
model = "GPT-4"
task = 'classification'

# Multi-line strings with triple quotes
prompt = """
You are a helpful AI assistant.
Please answer the following question:
"""

# Empty string
empty = ""

Booleans: True/False

Python
# Boolean values (note: capitalized)
is_training = True
use_gpu = False

# Booleans from comparisons
print(5 > 3)     # True
print(10 == 10)  # True
print(2 != 2)    # False

Type Conversion

Convert between types using built-in functions:

Python
# String to number
x = int("42")       # 42 (integer)
y = float("3.14")   # 3.14 (float)

# Number to string
s = str(100)        # "100"

# Float to int (truncates, doesn't round!)
n = int(3.9)        # 3 (not 4!)

# Boolean conversion
print(bool(1))       # True
print(bool(0))       # False
print(bool(""))      # False (empty string)
print(bool("hello")) # True

🤖 Types in AI Code

In AI, you'll work extensively with float for model weights, loss values, and probabilities. Libraries like NumPy and PyTorch add specialized types like float32 and float16 (half precision) for efficient GPU computation.

4 Operators

Arithmetic Operators

Python
a = 10
b = 3

print(a + b)   # 13   Addition
print(a - b)   # 7    Subtraction
print(a * b)   # 30   Multiplication
print(a / b)   # 3.33 Division (always float)
print(a // b)  # 3    Floor division (integer)
print(a % b)   # 1    Modulo (remainder)
print(a ** b)  # 1000 Exponentiation (10³)

Comparison Operators

Python
x = 5
y = 10

print(x == y)  # False  Equal to
print(x != y)  # True   Not equal to
print(x < y)   # True   Less than
print(x > y)   # False  Greater than
print(x <= y)  # True   Less than or equal
print(x >= y)  # False  Greater than or equal

⚠️ Common Mistake

= is assignment, == is comparison! Writing if x = 5 instead of if x == 5 is a syntax error.

Logical Operators

Python
is_trained = True
has_gpu = False
accuracy = 0.95

# and: both must be True
print(is_trained and has_gpu)    # False

# or: at least one must be True
print(is_trained or has_gpu)     # True

# not: inverts the boolean
print(not has_gpu)               # True

# Combining with comparisons
is_good_model = is_trained and accuracy > 0.9
print(is_good_model)             # True

Assignment Operators (Shortcuts)

Python
loss = 10.0

loss = loss - 0.1   # Subtract and reassign
loss -= 0.1         # Same thing, shorter!

# Other shortcuts
x = 5
x += 3   # x = x + 3  →  8
x *= 2   # x = x * 2  →  16
x /= 4   # x = x / 4  →  4.0
x **= 2  # x = x ** 2 →  16.0

5 Working with Strings

String Operations

Python
# Concatenation (joining)
first = "Hello"
second = "World"
combined = first + " " + second  # "Hello World"

# Repetition
dash = "-" * 20  # "--------------------"

# Length
print(len("Python"))  # 6

String Indexing and Slicing

Python
text = "Python"
#       012345  (index from 0)
#      -6-5-4-3-2-1 (negative index from end)

# Accessing characters
print(text[0])    # P (first character)
print(text[-1])   # n (last character)

# Slicing [start:end] (end is exclusive)
print(text[0:2])  # Py
print(text[2:])   # thon (from index 2 to end)
print(text[:3])   # Pyt (from start to index 3)
print(text[::2])  # Pto (every 2nd character)

String Methods

Python
text = "  Hello, World!  "

# Case conversion
print(text.lower())      # "  hello, world!  "
print(text.upper())      # "  HELLO, WORLD!  "

# Whitespace removal
print(text.strip())      # "Hello, World!"

# Search and replace
print(text.replace("World", "AI"))  # "  Hello, AI!  "

# Split into list
words = "apple,banana,cherry".split(",")
print(words)  # ['apple', 'banana', 'cherry']

# Join list into string
print(" ".join(words))  # "apple banana cherry"

f-Strings (Formatted Strings)

f-strings are the modern way to embed variables and expressions in strings:

Python
model = "GPT-4"
accuracy = 0.9543
epoch = 10

# f-string: prefix with f, use {variable}
message = f"Model: {model}, Accuracy: {accuracy}"
print(message)  # Model: GPT-4, Accuracy: 0.9543

# Formatting numbers
print(f"Accuracy: {accuracy:.2f}")    # 0.95 (2 decimal places)
print(f"Accuracy: {accuracy:.1%}")    # 95.4% (as percentage)
print(f"Epoch: {epoch:03d}")           # 010 (zero-padded)

# Expressions inside f-strings
print(f"Loss reduced by {100 * (1 - accuracy):.1f}%")

🤖 Strings in AI

Strings are everywhere in AI: prompts for language models, tokenized text, file paths for datasets, logging training progress. f-strings make it easy to create readable log messages: f"Epoch {epoch}: loss={loss:.4f}"

6 Practice Exercises

✏️ Exercise 1: Variables and Types

Create variables for: model name ("BERT"), number of parameters (110 million), whether it's pre-trained (yes). Print each variable and its type.
Click to reveal solution ▼
model_name = "BERT"
num_params = 110_000_000  # Underscores for readability!
is_pretrained = True

print(model_name, type(model_name))
print(num_params, type(num_params))
print(is_pretrained, type(is_pretrained))

✏️ Exercise 2: Arithmetic

A model trains for 50 epochs. Each epoch takes 3.5 minutes. Calculate total training time in hours.
Click to reveal solution ▼
epochs = 50
minutes_per_epoch = 3.5

total_minutes = epochs * minutes_per_epoch
total_hours = total_minutes / 60

print(f"Total training time: {total_hours:.2f} hours")
# Output: Total training time: 2.92 hours

✏️ Exercise 3: String Formatting

Create a training log message: "Epoch 5/100 - Loss: 0.2341 - Accuracy: 89.2%" Use variables: epoch=5, total_epochs=100, loss=0.2341, accuracy=0.892
Click to reveal solution ▼
epoch = 5
total_epochs = 100
loss = 0.2341
accuracy = 0.892

message = f"Epoch {epoch}/{total_epochs} - Loss: {loss:.4f} - Accuracy: {accuracy:.1%}"
print(message)
# Output: Epoch 5/100 - Loss: 0.2341 - Accuracy: 89.2%

🎯 Key Takeaways

  • Variables store data and use snake_case naming
  • Data types: int, float, str, bool, None—Python is dynamically typed
  • Operators: arithmetic (+, -, *, /, //, %, **), comparison (==, !=, <, >), logical (and, or, not)
  • Strings support indexing, slicing, and many useful methods
  • f-strings embed variables: f"Value: {x:.2f}"
  • type() tells you what type a value is

Next Steps

Now that you understand variables, types, and operators, you're ready to learn control flow—how to make decisions and repeat actions in your code.