Skip to main content
TensorFlow Introduction
CHAPTER 03 Intermediate

Python Basics for Deep Learning

Updated: May 16, 2026
5 min read

# CHAPTER 3

Python Basics for Deep Learning

1. Introduction

To build Artificial Intelligence, you must speak the language of AI. That language is Python. Python is 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 semi-colons. In this chapter, we will cover the core Python programming concepts—from variables to functions—that form the backbone of every TensorFlow workflow.

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.
python
1234567891011121314
# Integer (Epochs usually must be whole numbers)
epochs = 100

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

# String (Text data)
activation_function = "relu"

# Boolean (True/False flags)
use_gpu = True

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

4. Data Structures: Lists

In deep learning, you rarely process one number at a time. You process batches of numbers. 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. TensorFlow uses dictionaries extensively when passing configuration settings or returning training histories.
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.
python
123456789
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).
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.50196, 1.0]

9. Functions

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 throw an IndentationError.
  • Modifying a list while looping over it: Removing items from a list while currently iterating through it will cause the loop to skip items or crash.

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 model: learningrate of 0.01, batch_size of 32, and optimizer as "sgd".
  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.
  • Q: What is a List Comprehension, and why is it preferred over a standard for loop for simple transformations?

15. FAQs

Q: Do I need to be an expert Python software engineer to do Deep Learning? A: No. While advanced Python knowledge is great 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 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: ·