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.
Python has become the dominant language in AI and machine learning for several reasons:
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.
# 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.
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.
# 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
Model and model are differentif, for, class, etc.)learning_rate = 0.01
batch_size = 32
num_epochs = 10
model_v2 = "improved"
_hidden = 768
# 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
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.
Variables can be changed (reassigned) at any time:
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
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 |
# 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 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 = ""
# 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
Convert between types using built-in functions:
# 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
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.
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³)
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
= is assignment, == is comparison! Writing
if x = 5 instead of if x == 5 is a syntax error.
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
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
# Concatenation (joining)
first = "Hello"
second = "World"
combined = first + " " + second # "Hello World"
# Repetition
dash = "-" * 20 # "--------------------"
# Length
print(len("Python")) # 6
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)
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 are the modern way to embed variables and expressions in strings:
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 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}"
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))
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
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%
snake_case namingf"Value: {x:.2f}"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.