Skip to main content
PyTorch Essentials
CHAPTER 03 Intermediate

Python Basics for AI and Deep Learning

Updated: May 16, 2026
6 min read

# CHAPTER 3

Python Basics for AI and Deep Learning

1. Introduction

To build Artificial Intelligence, you must speak the language of AI. That language is Python. Python is universally favored by the Deep Learning community because its syntax is incredibly readable, allowing researchers to focus on complex neural network architectures rather than memory management or semicolons. In this chapter, we will cover the core Python programming concepts—from variables to functions—that form the backbone of every PyTorch script.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define variables and identify core data types.
  • Control program flow using if/else conditions.
  • Iterate through data using for and while loops.
  • Store collections of data in Lists and Dictionaries.
  • Write reusable functions.

3. Variables and Data Types

In Python, variables are created the moment you assign a value to them. You do not need to declare their type (e.g., int or string).
python
1234567891011121314
# Integer (Epochs must be whole numbers)
epochs = 100

# Float (Learning rates are almost always decimals)
learning_rate = 0.001

# String (Text data, like layer names)
activation_function = "relu"

# Boolean (True/False flags)
use_gpu = True

# Printing variables using f-strings
print(f"Training for {epochs} epochs using {activation_function}.")

4. Data Structures: Lists

In deep learning, you rarely process one number at a time. A Python List is an ordered, changeable collection of items.
python
1234567891011121314
# A list of loss values after each training step
loss_history = [0.95, 0.82, 0.71, 0.55, 0.42]

# Accessing the first item (0-indexed)
print(loss_history[0])  # Output: 0.95

# Accessing the last item
print(loss_history[-1]) # Output: 0.42

# Slicing (getting the first 3 items)
print(loss_history[0:3]) # Output: [0.95, 0.82, 0.71]

# Appending a new value
loss_history.append(0.35)

5. Data Structures: Dictionaries

Dictionaries store data in key: value pairs. PyTorch uses dictionaries extensively. When you save a model in PyTorch, you are actually saving a massive dictionary containing all the trained weights!
python
123456789101112131415
# Storing model configuration
model_config = {
    "layers": 3,
    "neurons_per_layer": 64,
    "optimizer": "adam"
}

# Accessing a value by its key
print(model_config["optimizer"]) # Output: adam

# Updating a value
model_config["layers"] = 5

# Adding a new key
model_config["dropout_rate"] = 0.2

6. Conditions (If / Else)

We use conditional logic to make decisions during training, such as stopping the training early if the model stops improving, or checking if a GPU is available.
python
1234567891011
device = "cuda" if use_gpu else "cpu"

current_accuracy = 0.92
target_accuracy = 0.95

if current_accuracy >= target_accuracy:
    print("Target reached! Stopping training.")
elif current_accuracy > 0.85:
    print("Getting close. Continue training.")
else:
    print("Accuracy is too low. Check the data.")

7. Loops (For and While)

Loops are how we iterate through massive datasets or repeat the training process (Epochs). As you will see later, PyTorch requires you to write the for loop manually for training!
python
1234567891011121314
# A 'for' loop iterating over a list
image_classes = ["Cat", "Dog", "Bird"]
for item in image_classes:
    print(f"Processing image of a {item}...")

# A 'for' loop using range (commonly used for epochs)
# This loops 3 times: 0, 1, 2
for epoch in range(3):
    print(f"Running Epoch {epoch + 1}")
    
# Output:
# Running Epoch 1
# Running Epoch 2
# Running Epoch 3

8. List Comprehensions

A highly efficient, "Pythonic" way to create a new list by transforming an existing list in a single line of code.
python
12345678
# Raw pixel values (0-255)
pixels = [0, 128, 255]

# Normalize pixels to be between 0 and 1
normalized = [p / 255.0 for p in pixels]

print(normalized) 
# Output: [0.0, 0.5019607843137255, 1.0]

9. Functions for AI Workflows

Functions allow you to encapsulate code into reusable blocks. In Deep Learning, you will often write custom functions to preprocess images or calculate specific error metrics.
python
1234567891011
def normalize_image(pixel_array):
    """
    Takes an array of pixels and scales them to 0-1.
    """
    clean_array = [p / 255.0 for p in pixel_array]
    return clean_array

# Calling the function
raw_image = [50, 100, 200]
ready_image = normalize_image(raw_image)
print(ready_image)

10. Common Mistakes

  • Indentation Errors: Python does not use {} brackets to define code blocks like C++ or Java. It uses whitespace (indentation). If you forget to indent the code inside a for loop or if statement, Python will crash with an IndentationError.
  • Zero-Indexing: Beginners often try to access the first item of a list using list[1]. In Python, the first item is always list[0].

11. Best Practices

  • Type Hinting: While Python doesn't require you to declare types, adding "Type Hints" makes deep learning code much easier to read and debug. (e.g., def train(epochs: int) -> float:)
  • Use standard naming conventions: Variables should be snakecase. Classes should be PascalCase.

12. Exercises

  1. 1. Create a dictionary that holds the hyperparameter settings for a mock PyTorch model: learningrate of 0.01, batch_size of 32, and device as "cuda".
  1. 2. Write a for loop that iterates from 1 to 5, printing "Training Epoch [number]" for each iteration.

13. MCQ Quiz with Answers

Question 1

Which data structure stores elements in Key-Value pairs?

Question 2

How does Python define the scope of a code block (like the code inside an if statement)?

14. Interview Questions

  • Q: Explain the difference between a List and a Dictionary in Python, and provide a deep learning use case for each.
  • Q: What is a List Comprehension, and why is it preferred over a standard for loop for simple data transformations?

15. FAQs

Q: Do I need to be an expert Python software engineer to do Deep Learning? A: No. While advanced Object-Oriented Python knowledge is necessary for production deployment, building and training AI models mostly requires a solid understanding of the basics covered here, plus a deep understanding of data manipulation libraries (which we cover next!).

16. Summary

Python's elegant and highly readable syntax is the foundation of modern AI development. By mastering variables, data structures like lists and dictionaries, control flow logic, and reusable functions, you possess the grammatical tools necessary to write complex machine learning scripts.

17. Next Chapter Recommendation

Standard Python lists are great, but they are far too slow for the millions of mathematical operations required by neural networks. In Chapter 4: NumPy, Pandas, and Data Handling, we will introduce the industry-standard libraries used to wrangle and manipulate massive datasets.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·