AI Engineer Program

Module 2: Python for AI Development

Learn the Python programming foundations needed to begin building practical AI applications.

📘

Beginner Technical Level

120–150 Minutes

🐍

Python Fundamentals

📅

Updated July 2026

Welcome to Python

Imagine that you have just been hired as a junior AI Engineer. On your first day, your manager asks you to build a simple application that reads customer information, sends a question to an AI model, and displays the AI's response.

What programming language would you choose?

Today, most AI engineers would answer with one word: Python.

Python has become the most widely used programming language in Artificial Intelligence, Machine Learning, Data Science, Scientific Computing, Automation, and many other fields. Whether you are building a chatbot, analysing medical data, developing an autonomous robot, or creating an intelligent recommendation system, there is a very good chance that Python is being used somewhere in the project.

But Python did not become popular simply because it is powerful. It became popular because it allows developers to solve complex problems using code that is clean, readable, and relatively easy to learn.

Throughout this module, you will begin writing Python programs from scratch. You will learn how computers store information, make decisions, repeat tasks, organise code, and interact with files. More importantly, you will begin thinking like a programmer—a skill that every AI engineer must develop.

💡Key Idea: Python is not just a programming language. It is the foundation upon which much of modern Artificial Intelligence is built.

By the end of this module, you will have written your own Python programs and built your first mini-project, providing a solid programming foundation for the AI, Machine Learning, and Data Science modules that follow.

Why Python Became the Language of AI

Artificial Intelligence requires developers to process large amounts of data, perform mathematical calculations, build predictive models, and interact with sophisticated software libraries.

Python makes all of these tasks easier.

  • Clean and readable syntax
  • Large collection of AI and Machine Learning libraries
  • Strong community support
  • Cross-platform compatibility
  • Excellent documentation
  • Integration with cloud platforms
  • Extensive use in research and industry

Because of these advantages, companies ranging from startups to global technology organizations use Python extensively in their AI projects.

Python Is Everywhere

Python is used in many different industries.

Industry Example Applications
Healthcare Disease prediction, medical imaging, clinical decision support
Finance Fraud detection, algorithmic trading, risk analysis
Education Intelligent tutoring systems, automated grading
Retail Product recommendations, demand forecasting
Manufacturing Predictive maintenance, quality control
Agriculture Crop monitoring, disease detection
Cybersecurity Threat detection, malware analysis
Scientific Research Data analysis, simulations, statistical modelling

As you can see, learning Python is not simply learning another programming language. It is acquiring a skill that is valuable across many professional domains.

AI Connection: Every major AI framework that you will encounter later in this program, including TensorFlow, PyTorch, Scikit-learn, LangChain, CrewAI, and the OpenAI SDK, uses Python. Learning Python is therefore one of the most important investments you can make as an aspiring AI Engineer.
⭐LearnerBox Pro Tip: Do not try to memorise Python syntax. Instead, focus on understanding how programs think and solve problems. Syntax becomes easier with regular practice.
🤔Did You Know? Python was created by Guido van Rossum and first released in 1991. The name "Python" does not come from the snake. It was inspired by the British comedy television series Monty Python's Flying Circus.

Learn more about Machine Learning and Deep Learning in our AI Guide series.

Running Python: VS Code and Google Colab

Before writing your first program, you need a place where Python code can be written and executed.

In the previous module, you learned about two important development environments:

  • Visual Studio Code (VS Code)
  • Google Colab

Both can run Python programs, but each serves a slightly different purpose. Professional AI engineers often use both depending on the task they are performing.

Running Python in Visual Studio Code

Visual Studio Code is one of the world's most popular development environments. It allows developers to create complete software projects consisting of many files, folders, and libraries.

Typical uses include:

  • Developing AI applications
  • Building web applications
  • Creating automation scripts
  • Writing APIs
  • Working on large software projects

VS Code is especially useful when your projects become more complex.

Advantages of VS Code

  • Fast and lightweight
  • Professional development environment
  • Excellent Git integration
  • Large extension ecosystem
  • Powerful debugging tools
  • Works offline
  • Suitable for large AI projects

Running Python in Google Colab

Google Colab provides an online notebook environment. Instead of installing software locally, your code runs on Google's cloud infrastructure.

Colab is particularly useful for:

  • Learning Python
  • Experimenting with Machine Learning
  • Data Science notebooks
  • Sharing work with classmates
  • Running code on GPUs

Advantages of Google Colab

  • No installation required
  • Accessible from anywhere
  • Free cloud computing
  • Automatic notebook saving
  • Easy collaboration

Comparing the Two

Visual Studio Code Google Colab
Professional software development Interactive notebooks
Local computer Cloud platform
Large projects Experiments and learning
Best for production code Best for exploration
Git integration Google Drive integration

Which Should You Use?

The answer is simple:

Use both.

During this course, small experiments can be performed in Google Colab, while larger projects should be developed in Visual Studio Code. Learning both environments prepares you for a wide variety of professional workflows.

AI Connection: Many AI researchers develop new ideas in Google Colab before moving their code into VS Code to build complete applications.
🚀Real-World Example: A Data Scientist may use Google Colab to experiment with a new Machine Learning model during the morning. Later, an AI Engineer takes that code, integrates it into a production application using VS Code, and deploys it for thousands of users.
⭐LearnerBox Pro Tip: Professional developers choose the tool that best suits the task. There is no "best" environment—only the environment that helps you work most effectively.
🧭Try It Yourself: Open both Visual Studio Code and Google Colab. Write the following program in each:

print("Hello LearnerBox!")

Notice how the development experience differs between the two environments.

Variables and Data Types

Imagine you are building an AI assistant for a university.

Every time a student asks a question, the program must remember:

  • the student's name
  • the question
  • the AI's answer
  • the date
  • whether the conversation has ended

Where does the program store all of this information?

The answer is:

Variables.

Variables are one of the most fundamental concepts in programming. Almost every program you will ever write, from a simple calculator to a sophisticated AI agent, relies on variables to temporarily store information while the program is running.

You can think of a variable as a labelled container. Instead of writing information directly into your program every time you need it, you store it inside a variable and refer to that variable whenever required. Variables allow AI systems to store information such as user input, predictions, or model parameters.

Creating Variables

name = "Aisha"
age = 22
course = "AI Engineer"
completed = True

Python automatically determines the type of data stored in each variable.

Common Data Types

Data Type Example Purpose
Integer 25 Whole numbers
Float 98.75 Decimal numbers
String "Hello" Text
Boolean True True/False values

Variable Naming Rules

Good variable names improve readability.

Good examples:

student_name
course_fee
total_marks
ai_model

Poor examples:

a
x1
temp2
data1234

Choose names that describe the information being stored.

Dynamic Typing

Unlike some programming languages, Python allows variables to change their type.

age = 20
age = "Twenty"

Although Python permits this, changing variable types unnecessarily can make programs difficult to understand.

⚠️Common Mistake: Many beginners confuse the assignment operator = with the equality operator ==. score = 90 assigns a value, while score == 90 checks whether two values are equal.
AI Connection: Every AI application uses variables continuously. Variables may store user prompts, API keys, model names, confidence scores, chatbot responses, prediction results, and image filenames.
💡Key Idea: Variables allow programs to remember information while they are running. They are the building blocks of every Python program.
⭐LearnerBox Pro Tip: Spend time choosing meaningful variable names. Professional developers often say that reading code should feel almost like reading English.
🧭Try It Yourself: Create variables that store your name, your favourite AI tool, your age, and whether you enjoy programming. Then display each variable using the print() function.

Operators and Expressions

Imagine you are developing an AI application that predicts whether a student qualifies for a scholarship.

The application needs to calculate averages, compare grades, determine eligibility, and combine several conditions before making a recommendation.

How does Python perform these calculations and comparisons?

The answer lies in operators.

Operators are symbols that instruct Python to perform actions on data. Just as mathematical operators such as + and − allow us to perform arithmetic, Python provides several types of operators for calculations, comparisons, logical decisions, and more.

Arithmetic Operators

Operator Purpose Example
+Addition5 + 3
-Subtraction8 - 2
*Multiplication6 * 7
/Division20 / 4
//Floor Division20 // 3
%Modulus20 % 3
**Exponent2 ** 5
price = 1500
tax = 270

total = price + tax

print(total)

Comparison Operators

Operator Meaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
marks = 82

print(marks >= 50)

Logical Operators

Operator Meaning
andBoth conditions must be true
orAt least one condition must be true
notReverses the result
age = 21
graduate = True

print(age >= 18 and graduate)

Membership Operators

subjects = ["Maths","Statistics","Python"]

print("Python" in subjects)

Identity Operators

a = [1,2,3]
b = a

print(a is b)

Identity operators are used less frequently by beginners but become important in advanced Python programming.

AI Connection: AI systems constantly perform comparisons. For example:
  • Is confidence greater than 90%?
  • Is the detected object a pedestrian?
  • Has the chatbot received a valid prompt?
  • Does the user's subscription allow GPT-4 access?
⚠️Common Mistake: Remember that = assigns a value, whereas == compares two values.
💡Key Idea: Operators allow programs to calculate, compare, and make decisions.
🧭Try It Yourself: Create variables storing:
  • Your age
  • Your course fee
  • Your examination score
Write expressions that calculate:
  • Fee after a discount
  • Whether your score is above 80
  • Whether you are over 18 and enrolled in the AI Engineer program

Input and Output

Programming becomes much more interesting when users can interact with our programs.

So far, we have only displayed information using the print() function.

Real applications also accept information from users.

This is called input.

Displaying Information

print("Welcome to LearnerBox")

Receiving User Input

name = input("Enter your name: ")

print("Welcome", name)

Converting Input

age = int(input("Enter your age: "))

price = float(input("Enter the price: "))

Formatting Output

name = "Aisha"

print(f"Welcome {name}")
AI Connection: Almost every AI application accepts user input.
  • Chatbot questions
  • Uploaded documents
  • Images
  • Voice recordings
  • Customer requests
🚀Real-World Example: Every prompt typed into ChatGPT is user input that is processed before the model generates a response.
⭐LearnerBox Pro Tip: Learn f-strings early. Professional Python developers use them extensively because they make programs easier to read and maintain.
🧭Try It Yourself: Write a program that asks the user for:
  • Name
  • Favourite AI tool
  • Career goal
Display the answers using f-strings.

Conditional Statements

Suppose you are developing an AI system for an online examination.

The system must determine whether a student passed, whether a loan application should be approved, whether an email is spam, or whether a customer receives a discount.

How does software make these decisions?

Through conditional statements.

Conditional statements allow programs to choose different actions depending on conditions.

The if Statement

marks = 82

if marks >= 50:
    print("Pass")

The if...else Statement

marks = 42

if marks >= 50:
    print("Pass")
else:
    print("Fail")

The if...elif...else Structure

marks = 75

if marks >= 90:
    print("Excellent")
elif marks >= 75:
    print("Very Good")
elif marks >= 50:
    print("Pass")
else:
    print("Fail")

Nested Conditions

age = 22
graduate = True

if age >= 18:
    if graduate:
        print("Eligible")

Indentation Matters

if age >= 18:
    print("Adult")
AI Connection: AI models constantly make decisions.
  • Should an email be classified as spam?
  • Is a medical image normal?
  • Should the chatbot ask another question?
  • Which product should be recommended?
🏢Industry Insight: Modern AI systems often combine machine learning predictions with traditional conditional logic. For example, a fraud detection system may block transactions whose fraud probability exceeds 90%, send medium-risk transactions for manual review, and approve the rest.
⚠️Common Mistake: Python uses indentation—not braces—to define blocks of code.
💡Key Idea: Conditional statements allow software to make intelligent decisions.
🧭Try It Yourself: Write a program that asks for an examination score and displays:
  • Distinction (90 or above)
  • First Class (75–89)
  • Pass (50–74)
  • Fail (below 50)

Loops

Imagine you are developing an AI application that must analyse one thousand customer reviews.

Would you write the same piece of code one thousand times?

Of course not. Instead, you tell the computer: repeat this task for every review.

This is exactly what loops allow us to do. AI applications frequently process thousands or millions of records. Loops automate repetitive tasks efficiently.

Why Loops Matter

  • Analysing thousands of images
  • Processing customer feedback
  • Training machine learning models
  • Reading large datasets
  • Sending API requests
  • Evaluating prediction results

The for Loop

for number in range(5):
    print(number)

Looping Through a List

languages = ["Python", "SQL", "R"]

for language in languages:
    print(language)

The while Loop

count = 1

while count <= 5:
    print(count)
    count += 1

break and continue

for number in range(10):
    if number == 5:
        break

    print(number)
for number in range(5):
    if number == 2:
        continue

    print(number)
AI Connection: Loops appear everywhere in Artificial Intelligence, including training models, processing datasets, generating embeddings, and calling AI APIs repeatedly.
🏢Industry Insight: Training a Large Language Model may involve repeating calculations over trillions of words. Although the systems are highly sophisticated, repetition remains one of the foundations of AI.
⚠️Common Mistake: Beginners sometimes forget to update the loop variable inside a while loop, creating an infinite loop.
💡Key Idea: Loops allow computers to automate repetitive tasks efficiently.
🧭Try It Yourself: Write a program that prints numbers from 1 to 20. Then modify it to display only even numbers. Finally, create a list of five AI tools and display each tool using a for loop.

Functions

Imagine building an AI chatbot containing one thousand lines of code. Suppose the chatbot needs to greet users. Would you write the greeting code fifty different times?

Professional programmers avoid repetition. Instead, they create functions.

A function is a reusable block of code that performs a specific task.

Creating a Function

def greet():
    print("Welcome to LearnerBox")

greet()

Functions with Parameters

def greet(name):
    print(f"Welcome {name}")

greet("Aisha")

Returning Values

def square(number):
    return number ** 2

answer = square(8)

print(answer)

Variable Scope

Variables created inside a function usually exist only within that function.

def demo():
    message = "Hello"
AI Connection: Modern AI software consists of many functions. One function may clean data, another may call an API, another may generate embeddings, and another may display predictions. Large AI systems consist of thousands of reusable functions working together.
🚀Real-World Example: When you ask ChatGPT a question, many internal functions process the prompt, retrieve information, generate tokens, apply safety checks, and return the final response.
⭐LearnerBox Pro Tip: Try to make each function perform one clearly defined task.
⚠️Common Mistake: Many beginners write one enormous function containing hundreds of lines. Professional developers prefer smaller, well-named functions.
💡Key Idea: Functions are the building blocks of professional software development.
🧭Try It Yourself: Write a function that calculates the area of a rectangle. Then write another function that greets a user by name. Finally, create a function that returns the square of a number.

Python Data Structures

Suppose you are building an AI assistant for a university. The assistant needs to store student names, examination marks, course information, departments, and attendance records.

Using separate variables for every piece of information would quickly become impossible. Instead, Python provides data structures. Choosing the right data structure makes AI programs easier to understand and more efficient.

Lists

students = ["Aisha", "Rahul", "Fatima"]

Lists are ordered, changeable, and allow duplicates.

Tuples

coordinates = (15.2, 27.8)

Tuples are useful when information should remain constant.

Sets

subjects = {"Python", "Statistics", "AI"}

Sets store unique values and automatically remove duplicates.

Dictionaries

student = {
    "name": "Aisha",
    "marks": 91,
    "course": "AI Engineer"
}

Dictionaries store information as key-value pairs and are heavily used in AI applications.

Comparing Data Structures

Structure Ordered Changeable Duplicates
ListYesYesYes
TupleYesNoYes
SetNoYesNo
DictionaryYesYesKeys unique
AI Connection: Every AI application uses data structures to store chatbot conversations, prediction results, model settings, API responses, configuration files, and datasets.
🏢Industry Insight: Most AI APIs exchange information using JSON, which is essentially a collection of dictionaries and lists.
💡Key Idea: Data structures organize information efficiently.
⭐LearnerBox Pro Tip: When unsure, start with a list. As your understanding grows, you will naturally recognize when tuples, sets, or dictionaries are more appropriate.
🧭Try It Yourself: Create a list of five AI libraries, a tuple storing coordinates, a set of programming languages, and a dictionary describing yourself.

Working with Files

Imagine you are building an AI application that analyses customer feedback stored in a text file. Before the AI model can process the information, your Python program must first read the file.

Opening a File

file = open("notes.txt", "r")

Reading a File

file = open("notes.txt", "r")

content = file.read()

print(content)

file.close()

Writing to a File

file = open("notes.txt", "w")

file.write("Welcome to LearnerBox!")

file.close()

Appending to a File

file = open("notes.txt", "a")

file.write("\nPython is fun!")

file.close()

Using the with Statement

with open("notes.txt", "r") as file:
    content = file.read()

print(content)
AI Connection: AI systems regularly read datasets, configuration files, prompts, documents, PDFs, images, and CSV files.
🏢Industry Insight: Before a machine learning model can be trained, data engineers often write Python programs that read millions of rows from CSV files before cleaning and transforming the data.
⭐LearnerBox Pro Tip: Whenever possible, use the with statement instead of manually calling close().
🧭Try It Yourself: Create a text file called my_notes.txt. Write three reasons why you want to learn AI. Then write a Python program that reads and displays the file.

Handling Errors

No programmer writes perfect code. Even experienced AI engineers make mistakes every day. The difference is that experienced developers know how to identify and handle errors effectively.

What Is an Exception?

An exception occurs whenever Python encounters an unexpected situation.

  • Dividing by zero
  • Opening a file that does not exist
  • Entering text when a number is expected

Using try and except

try:
    number = int(input("Enter a number: "))
    print(number)
except:
    print("Invalid input")

Multiple Exceptions

try:
    number = int(input())
except ValueError:
    print("Please enter a valid number.")

finally

try:
    print("Running program")
finally:
    print("Program finished")
AI Connection: If an AI application calls an online API, the internet connection may fail, the server may be unavailable, or the API key may be invalid. Exception handling helps prevent the application from crashing.
🚀Real-World Example: A banking chatbot cannot simply stop working because one API request fails. Instead, it should display a helpful message and protect the user experience.
⚠️Common Mistake: Avoid using a blank except: whenever possible. Catch specific exceptions to make debugging easier.
💡Key Idea: Good software does not avoid errors. Good software handles errors gracefully.
🧭Try It Yourself: Write a program that asks the user to enter their age. If the user enters text instead of a number, display a friendly error message.

Installing Python Libraries

One of Python's greatest strengths is its enormous ecosystem of libraries. Instead of writing everything yourself, you can use software written by other developers.

What Is a Library?

Libraries allow developers to build upon existing work instead of starting from scratch.

Installing Libraries

pip install pandas
pip install numpy

Importing Libraries

import pandas

import numpy as np

Popular Libraries for AI Engineers

Library Purpose
NumPyNumerical computing
PandasData analysis
MatplotlibData visualization
Scikit-learnMachine Learning
TensorFlowDeep Learning
PyTorchDeep Learning
OpenAI SDKBuilding AI applications
LangChainLLM application development
FastAPIBuilding APIs
AI Connection: Modern AI would not exist without open-source libraries. Thousands of researchers and engineers contribute to libraries that help developers build sophisticated AI systems efficiently.
⭐LearnerBox Pro Tip: You do not need to memorise every library. Focus on understanding what each library is designed to do.

You will soon work with libraries such as NumPy, Pandas, and Matplotlib in Module 3.

Mini Project: Student Record Manager

In this mini project, you will combine many of the concepts learned in this module.

Project Requirements

Write a Python program that:

  • asks the user for their name
  • asks for three examination marks
  • calculates the average
  • determines whether the student passed
  • displays the result
  • stores the information in a text file

Skills Practised

  • Variables
  • Data types
  • Operators
  • Input
  • Conditional statements
  • Functions
  • File handling

Stretch Challenge

  • Calculate grades
  • Handle invalid input
  • Allow multiple students
  • Save results for every student
🏢Industry Insight: Although this project is simple, professional software systems are built using exactly the same programming concepts. The difference is not the concepts—it is the scale.

Upload this project to the GitHub repository you created in Module 1 and write a short README describing:

  • what the program does
  • what you learned
  • one improvement you would make

Module Summary

Congratulations! You have completed your first Python programming module.

More importantly, you have begun developing the mindset of a software engineer.

In This Module You Learned

  • Why Python powers modern AI
  • Running Python in VS Code and Google Colab
  • Variables and data types
  • Operators and expressions
  • User input and formatted output
  • Conditional statements
  • Loops
  • Functions
  • Python data structures
  • File handling
  • Exception handling
  • Python libraries
  • Building your first Python application
💡Key Idea: Programming is not about memorising syntax. Programming is about solving problems logically and systematically.

Looking Ahead

You can now write Python programs that solve problems. In the next module, you will apply those programming skills to real-world datasets, discovering how AI engineers clean, analyse, and visualize data before building machine learning models.

Reflection & Knowledge Check

Reflection

Take a few minutes to think about your learning.

  1. Which Python concept did you find the easiest to understand, and why?
  2. Which concept do you think will require more practice?
  3. How do you think Python will help you as an AI Engineer?
  4. Which AI application would you like to build one day?
  5. What is one programming habit you will develop after completing this module?

Knowledge Check

  1. Why has Python become the preferred programming language for Artificial Intelligence?
  2. What is the difference between a for loop and a while loop?
  3. Why are functions important in professional software development?
  4. Which Python data structure would you use to store information about a student and why?
  5. What is the purpose of the try and except statements?
⭐LearnerBox Pro Tip: Do not worry if you cannot write every program without looking at examples. Professional developers regularly consult documentation, search for solutions, and learn from previous code.

You have successfully completed the module content. Ready to Test What You Learned?

Take a short Quiz and find your score. You can always come back to this page and go through the content again!