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.
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.
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.
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.
= with the equality operator ==. score = 90
assigns a value, while score == 90 checks whether two values are equal.
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 |
|---|---|---|
| + | Addition | 5 + 3 |
| - | Subtraction | 8 - 2 |
| * | Multiplication | 6 * 7 |
| / | Division | 20 / 4 |
| // | Floor Division | 20 // 3 |
| % | Modulus | 20 % 3 |
| ** | Exponent | 2 ** 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 |
|---|---|
| and | Both conditions must be true |
| or | At least one condition must be true |
| not | Reverses 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.
- 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?
= assigns a value, whereas
== compares two values.
- Your age
- Your course fee
- Your examination score
- 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}")
- Chatbot questions
- Uploaded documents
- Images
- Voice recordings
- Customer requests
- Name
- Favourite AI tool
- Career goal
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")
- Should an email be classified as spam?
- Is a medical image normal?
- Should the chatbot ask another question?
- Which product should be recommended?
- 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)
while loop, creating an infinite loop.
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"
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 |
|---|---|---|---|
| List | Yes | Yes | Yes |
| Tuple | Yes | No | Yes |
| Set | No | Yes | No |
| Dictionary | Yes | Yes | Keys unique |
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)
with statement instead of manually
calling close().
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")
except: whenever possible. Catch specific
exceptions to make debugging easier.
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 |
|---|---|
| NumPy | Numerical computing |
| Pandas | Data analysis |
| Matplotlib | Data visualization |
| Scikit-learn | Machine Learning |
| TensorFlow | Deep Learning |
| PyTorch | Deep Learning |
| OpenAI SDK | Building AI applications |
| LangChain | LLM application development |
| FastAPI | Building APIs |
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
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
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.
- Which Python concept did you find the easiest to understand, and why?
- Which concept do you think will require more practice?
- How do you think Python will help you as an AI Engineer?
- Which AI application would you like to build one day?
- What is one programming habit you will develop after completing this module?
Knowledge Check
- Why has Python become the preferred programming language for Artificial Intelligence?
- What is the difference between a
forloop and awhileloop? - Why are functions important in professional software development?
- Which Python data structure would you use to store information about a student and why?
- What is the purpose of the
tryandexceptstatements?