📚 Welcome to Python with AI
Python is the #1 programming language in the world for 7 consecutive years (Stack Overflow 2024). It powers everything from web development to data science, machine learning, AI automation and ChatGPT itself. Learning Python with AI gives you one of the most sought-after skill combinations in 2026.
This course takes you from zero Python knowledge to building real AI-powered applications — including integrating with the ChatGPT API, automating business tasks with AI and applying machine learning to real datasets.
💡 How to use this page: Click any topic in the left sidebar. All notes load instantly — no page reloads. Every section has real code examples you can copy and run. Use the Prev / Next buttons to go in order.
🐍 Python Basics
BeginnerWhy Python? Key Advantages
| Feature | What It Means | Real Benefit |
|---|---|---|
| Simple Syntax | Reads almost like English | Learn in weeks, not months. Less time debugging syntax errors. |
| Interpreted | Runs line by line — no compilation | Instant feedback. Great for prototyping and data work. |
| Dynamically Typed | No need to declare variable types | Faster to write: x = 5 works immediately |
| Huge Library Ecosystem | 300,000+ packages on PyPI | Almost any problem has a ready-made library |
| Cross-Platform | Runs on Windows, Mac, Linux | Write once, run anywhere |
| AI/ML Standard | TensorFlow, PyTorch, Scikit-learn all use Python | The language of AI — no alternative |
Variables & Data Types
# Python is dynamically typed — no type declaration needed
name = "Hari Krishna" # str
age = 42 # int
salary = 25.5 # float (lakhs)
is_active= True # bool
# Check type anytime
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
# f-strings — the modern way to format strings
print(f"Hello {name}, you are {age} years old")
# Output: Hello Hari Krishna, you are 42 years old
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0 # All three = 0
Control Flow — if / elif / else
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B") # This runs — score is 85
elif score >= 60:
print("Grade: C")
else:
print("Fail")
# One-line if (ternary)
result = "Pass" if score >= 60 else "Fail"
Loops — for and while
# for loop — most common in Python
courses = ["SAP", "Python", "AI", "Leadership"]
for course in courses:
print(f"Course: {course}")
# range() — for numeric loops
for i in range(1, 6): # 1 to 5
print(f"Count: {i}")
# enumerate() — get index AND value
for idx, course in enumerate(courses, 1):
print(f"{idx}. {course}")
# List comprehension — Python's superpower
lengths = [len(c) for c in courses]
# [3, 6, 2, 10]
# while loop
count = 0
while count < 3:
print(f"Attempt {count + 1}")
count += 1
Functions — The Building Blocks
# Basic function
def greet(name):
return f"Hello, {name}!"
print(greet("Hari Krishna")) # Hello, Hari Krishna!
# Default parameters
def calculate_fee(course, duration=30, discount=0):
base = 500 * duration
return base * (1 - discount / 100)
print(calculate_fee("Python")) # 15000
print(calculate_fee("SAP", 60, 10)) # 27000
# *args and **kwargs
def show_courses(*args, **kwargs):
print("Courses:", args)
print("Details:", kwargs)
show_courses("Python", "SAP", city="Bangalore", batch="Morning")
💡 Python Best Practices: Use meaningful variable names. Follow PEP 8 (Python's style guide) — 4 spaces for indentation, snake_case for variables, PascalCase for classes. Write docstrings for all functions. Keep functions short — one function, one job.
🎲 Object-Oriented Programming in Python
IntermediateOOP is a programming paradigm that organises code into objects — bundles of data (attributes) and behaviour (methods). Python supports all 4 pillars of OOP — encapsulation, inheritance, polymorphism and abstraction.
Classes and Objects — The Foundation
class Trainer:
"""Represents a corporate trainer at Cuesys Infotech"""
# Class variable — shared by ALL instances
company = "Cuesys Infotech Pvt Ltd"
# __init__ = constructor — runs when object is created
def __init__(self, name, expertise, years_exp):
self.name = name # instance variables
self.expertise = expertise
self.years_exp = years_exp
self.courses = []
def add_course(self, course):
self.courses.append(course)
def introduce(self):
return (f"I am {self.name}, {self.years_exp}-year expert in "
f"{self.expertise} at {self.company}")
# __str__ = controls print() output
def __str__(self):
return f"Trainer: {self.name} | {self.expertise}"
# Create objects (instances)
hari = Trainer("Hari Krishna", "SAP Security & AI", 16)
hari.add_course("SAP GRC")
hari.add_course("Python with AI")
print(hari.introduce())
print(hari.courses) # ['SAP GRC', 'Python with AI']
Inheritance — Reusing and Extending Classes
class SeniorTrainer(Trainer): # Inherits from Trainer
def __init__(self, name, expertise, years_exp, award):
super().__init__(name, expertise, years_exp) # parent init
self.award = award # new attribute
# Override parent method (polymorphism)
def introduce(self):
base = super().introduce()
return f"{base} | Award: {self.award}"
senior = SeniorTrainer(
"Hari Krishna", "SAP & AI", 16,
"Silicon India Top 10 — 2022"
)
print(senior.introduce())
print(isinstance(senior, Trainer)) # True — IS a Trainer
The 4 Pillars of OOP — Quick Reference
| Pillar | Definition | Python Implementation | Purpose |
|---|---|---|---|
| Encapsulation | Bundle data + methods together. Hide internal details. | Use _ (protected) or __ (private) prefix. Expose via properties. | Security, controlled access, reduced complexity |
| Inheritance | Child class inherits attributes and methods from parent class. | class Child(Parent): — use super() to call parent methods. | Code reuse, hierarchical relationships, extensibility |
| Polymorphism | Same method name behaves differently in different classes. | Override parent methods in child classes. Duck typing in Python. | Flexible, extensible code — "one interface, many forms" |
| Abstraction | Show only what is necessary, hide implementation details. | Use ABC module: from abc import ABC, abstractmethod | Reduces complexity, enforces interface contracts |
📚 Python Data Structures
Beginner → IntermediateThe 4 Built-in Data Structures
| Type | Syntax | Ordered? | Mutable? | Duplicates? | Best Use |
|---|---|---|---|---|---|
| List | [1, 2, 3] | ✅ Yes | ✅ Yes | ✅ Yes | Ordered collections that change — course list, scores |
| Tuple | (1, 2, 3) | ✅ Yes | ❌ No | ✅ Yes | Fixed data — coordinates, RGB values, database records |
| Set | {1, 2, 3} | ❌ No | ✅ Yes | ❌ No | Unique items — removing duplicates, membership testing |
| Dictionary | {"k": "v"} | ✅ Yes* | ✅ Yes | Keys: No | Key-value pairs — JSON data, config, lookup tables |
Dictionary — Most Important for AI Work
# Create a dictionary (like JSON)
student = {
"name": "Ravi Kumar",
"course": "Python with AI",
"score": 92,
"passed": True
}
# Access values
print(student["name"]) # Ravi Kumar
print(student.get("age", "N/A")) # N/A (safe — no KeyError)
# Add / Update
student["city"] = "Bangalore"
student["score"] = 95
# Loop through
for key, value in student.items():
print(f" {key}: {value}")
# Dictionary comprehension
scores = {"Ravi": 85, "Priya": 92, "Arjun": 78}
passed = {k: v for k, v in scores.items() if v >= 80}
# {'Ravi': 85, 'Priya': 92}
📄 Files & Error Handling
IntermediateReading and Writing Files
# Writing a file — 'w' overwrites, 'a' appends
with open("students.txt", "w") as f:
f.write("Ravi Kumar, Python with AI\n")
f.write("Priya Sharma, SAP Security\n")
# Reading a file
with open("students.txt", "r") as f:
content = f.read() # Entire file as string
lines = f.readlines() # List of lines
# Working with CSV using csv module
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f) # Each row as a dict
for row in reader:
print(row["name"], row["score"])
Exception Handling — try / except / finally
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError as e:
print(f"Type error: {e}")
return None
finally:
print("This ALWAYS runs — cleanup code here")
# Custom exceptions
class InsufficientScoreError(Exception):
def __init__(self, score, minimum):
super().__init__(f"Score {score} is below minimum {minimum}")
def certify(score):
if score < 70:
raise InsufficientScoreError(score, 70)
📊 Data Science — NumPy, Pandas & Matplotlib
IntermediateThe Data Science Trinity — NumPy for numerical computing, Pandas for data manipulation and Matplotlib for visualisation. These three libraries are used in virtually every data science and AI project.
Pandas — Data Manipulation
import pandas as pd
# Create DataFrame (table)
data = {
"name": ["Ravi", "Priya", "Arjun", "Sneha"],
"course": ["SAP", "Python", "SAP", "Python"],
"score": [85, 92, 78, 96],
"passed": [True, True, True, True]
}
df = pd.DataFrame(data)
# Essential operations
print(df.head()) # First 5 rows
print(df.describe()) # Stats: mean, std, min, max
print(df.info()) # Column types, null counts
# Filtering
python_students = df[df["course"] == "Python"]
high_scorers = df[df["score"] >= 90]
# Aggregation
print(df.groupby("course")["score"].mean())
# SAP: 81.5, Python: 94.0
# Load from CSV / Excel
df = pd.read_csv("training_data.csv")
df = pd.read_excel("training_data.xlsx")
NumPy — Fast Numerical Computing
import numpy as np
scores = np.array([85, 92, 78, 96, 88])
print(np.mean(scores)) # 87.8
print(np.std(scores)) # standard deviation
print(np.max(scores)) # 96
print(scores[scores > 85]) # [92 96 88] — boolean indexing
# Why NumPy? 100x faster than plain Python lists for math
# All ML libraries use NumPy arrays internally
🤖 Machine Learning with Python
Intermediate → AdvancedMachine Learning is teaching computers to learn from data without explicitly programming every rule. Python's Scikit-learn library makes it possible to build ML models in just 5–10 lines of code.
The ML Workflow — 5 Steps Every Project Follows
Classification Model — Predict Pass or Fail
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
# 1. Load data
df = pd.read_csv("student_data.csv")
# 2. Features (X) and Target (y)
X = df[["attendance", "assignment_score", "mock_test"]]
y = df["passed"] # 1 = passed, 0 = failed
# 3. Split — 80% train, 20% test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 4. Train
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# 5. Evaluate
predictions = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, predictions):.2%}")
print(classification_report(y_test, predictions))
# 6. Predict new student
new_student = [[85, 78, 82]] # attendance, assignment, mock
result = model.predict(new_student)
print("Predicted:", "Pass" if result[0] == 1 else "Fail")
Common ML Algorithms — When to Use Which
| Algorithm | Type | Use When | Sklearn Class |
|---|---|---|---|
| Linear Regression | Regression | Predicting a number (salary, price, score) | LinearRegression() |
| Logistic Regression | Classification | Binary classification (pass/fail, yes/no) | LogisticRegression() |
| Decision Tree | Both | Interpretable rules needed, non-linear data | DecisionTreeClassifier() |
| Random Forest | Both | High accuracy, handles missing data well | RandomForestClassifier() |
| K-Means | Clustering | Grouping similar items (customer segments) | KMeans(n_clusters=3) |
| SVM | Classification | High-dimensional data, text classification | SVC() |
🧠 ChatGPT API Integration with Python
AdvancedThe OpenAI API lets you call GPT-4o directly from your Python code — build AI chatbots, document analysers, email drafters, content generators and much more. This is the most in-demand skill in 2026.
Setup — Install and Configure
pip install openai python-dotenv
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv() # Load API key from .env file
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
response = client.chat.completions.create(
model = "gpt-4o",
messages= [
{"role": "system", "content": "You are a helpful SAP training assistant."},
{"role": "user", "content": "Explain SAP GRC in 3 bullet points"}
]
)
answer = response.choices[0].message.content
print(answer)
Real Project — AI Email Drafter for Cuesys
from openai import OpenAI
client = OpenAI()
def draft_training_proposal(company, course, employees, duration):
prompt = f"""
Write a professional corporate training proposal email for:
- Company: {company}
- Course: {course}
- Number of employees: {employees}
- Duration: {duration}
- Training provider: Cuesys Infotech Pvt Ltd, Bangalore
- Award: Silicon India Top 10 Corporate Training Startups 2022
Tone: Professional, confident, persuasive.
Include: Benefits, brief agenda, call to action.
Length: Under 200 words.
"""
response = client.chat.completions.create(
model = "gpt-4o",
messages= [{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# Use it!
email = draft_training_proposal(
"Infosys BPM", "SAP Security & GRC", 50, "3 days"
)
print(email)
Key API Parameters Explained
| Parameter | Values | Effect |
|---|---|---|
| model | gpt-4o, gpt-4o-mini, gpt-3.5-turbo | Which model to use — 4o is best, mini is cheaper |
| temperature | 0.0 – 2.0 | 0 = deterministic/focused. 1 = balanced. 2 = very creative/random. Use 0 for factual tasks, 0.7 for creative. |
| max_tokens | 1 – 4096 | Maximum length of response. 1 token ≈ ¾ word. Set to control costs. |
| messages | List of {role, content} | system = AI's persona. user = your question. assistant = previous AI reply (for conversations). |
| stream | True / False | True = stream tokens as they generate (like ChatGPT). False = wait for full response. |
⚠ Cost & Safety Tips: Always store your API key in a .env file — never hardcode it in your script. Set max_tokens limits to control costs. Use gpt-4o-mini for development and testing (10x cheaper). Monitor usage at platform.openai.com/usage.
⚙️ AI Automation with Python
AdvancedPython + AI = the ultimate automation stack. You can automate Excel reports, send emails, scrape websites, process PDFs and even schedule tasks — all enhanced with AI intelligence.
Automate Excel Reports with openpyxl + AI
import openpyxl
from openpyxl.styles import Font, PatternFill
from openai import OpenAI
client = OpenAI()
# 1. Load Excel data
wb = openpyxl.load_workbook("training_report.xlsx")
ws = wb.active
# 2. Read data into summary text
data_text = ""
for row in ws.iter_rows(values_only=True):
data_text += str(row) + "\n"
# 3. Ask AI to analyse and give insights
response = client.chat.completions.create(
model = "gpt-4o",
messages= [{"role":"user", "content":
f"Analyse this training data and give 3 key insights:\n{data_text}"}]
)
# 4. Write AI insights back to Excel
insights = response.choices[0].message.content
ws["A20"] = "AI Analysis:"
ws["A20"].font = Font(bold=True, color="1565C0")
ws["A21"] = insights
wb.save("training_report_AI.xlsx")
Top Python Automation Libraries
| Library | Purpose | Install |
|---|---|---|
| openpyxl | Read/write Excel files (.xlsx) | pip install openpyxl |
| smtplib | Send emails (built-in Python) | Built-in — no install |
| requests | Call any web API or URL | pip install requests |
| BeautifulSoup | Web scraping — extract data from websites | pip install beautifulsoup4 |
| PyPDF2 / pdfplumber | Read and extract text from PDFs | pip install pdfplumber |
| schedule | Schedule tasks to run automatically | pip install schedule |
| Selenium | Browser automation — fill forms, click buttons | pip install selenium |
| python-docx | Create and edit Word documents | pip install python-docx |
💻 5 Real-World Projects for Your Resume
All LevelsNothing proves your Python skills better than real projects. These 5 projects are specifically designed to demonstrate Python + AI capabilities to employers and clients.
Beginner
Takes company name, course and headcount → generates a professional training proposal email using GPT-4o → saves as a Word document.
Intermediate
Takes student attendance, assignment scores and mock test results → uses Random Forest ML model → predicts if they will pass the certification exam.
Intermediate
A command-line chatbot that answers questions about Cuesys courses using GPT-4o with a custom system prompt and conversation history.
Intermediate
Reads training data from Excel → generates attendance charts, score distributions and trends → exports a formatted PDF report automatically.
Advanced
Upload a resume PDF → Python extracts text → GPT-4o scores it against a job description → gives detailed feedback and improvement suggestions.
❓ Python with AI — Interview Q&A
Most frequently asked Python and AI questions at IT companies, MNCs, startups and data science roles. Click each question to reveal the model answer.
Model Answer:
Python has several characteristics that make it the language of choice for AI/ML: (1) Simple, readable syntax — data scientists can focus on algorithms rather than language complexity. (2) Massive ecosystem — TensorFlow, PyTorch, Scikit-learn, Pandas, NumPy all have Python as their primary interface. (3) Interpreted and interactive — Jupyter notebooks allow exploration and experimentation in real time. (4) Strong community — largest ML community means abundant tutorials, pre-built models and Stack Overflow support. (5) Integration capability — Python interfaces easily with C/C++ for performance-critical code (NumPy internals are in C). (6) Cross-platform — runs identically on Windows, Mac and Linux, which is important for deploying ML models across environments.
Model Answer:
Both are ordered sequences in Python, but they differ in mutability and use cases. A list (created with square brackets []) is mutable — you can add, remove and change items after creation. A tuple (created with parentheses ()) is immutable — once created, it cannot be changed. Performance: tuples are faster and use less memory than lists. Use lists when data changes frequently — a running total, a growing dataset. Use tuples when data is fixed — coordinates (x, y), RGB values (255, 128, 0), database row records. Tuples can be used as dictionary keys (because they are hashable); lists cannot. In practice: function returns multiple values as a tuple; API calls typically return mutable lists of results.
Model Answer:
__new__ is the constructor — it creates and returns the new instance of the class. __init__ is the initialiser — it sets up the initial state (attributes) of the already-created instance. In practice, you almost never need to override __new__. You override __init__ to accept parameters and assign instance variables. __new__ receives the class itself as the first argument; __init__ receives the new instance (self). __new__ returns an instance; __init__ returns nothing (implicitly None). Singleton pattern is one case where __new__ is overridden — to ensure only one instance exists. For 99% of Python programming, understanding and using __init__ correctly is all you need.
Model Answer:
A decorator is a function that wraps another function to extend its behaviour without modifying it. They use the @ syntax. Real example — a timer decorator:\n\nimport time\ndef timer(func):\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n print(f"{func.__name__} took {time.time()-start:.2f}s")\n return result\n return wrapper\n\n@timer\ndef train_model(data):\n # expensive operation\n pass\n\nCommon built-in decorators: @staticmethod (no self/cls needed), @classmethod (receives class not instance), @property (access method like attribute). Frameworks use decorators heavily — @app.route() in Flask, @pytest.fixture in testing, @login_required in Django.
Model Answer:
The OpenAI API provides programmatic access to GPT-4o. The workflow: (1) Install the OpenAI Python library. (2) Store the API key securely in a .env file. (3) Call client.chat.completions.create() with a model name, and a messages list containing system (AI persona) and user (the question) roles. (4) Extract the response from response.choices[0].message.content. Business application example — a training proposal generator: accept company name, course and headcount as input, craft a structured prompt, call the API, and return a formatted email or Word document. Key considerations: (a) Use a system prompt to define the AI's role and tone. (b) Set temperature=0 for factual/structured output. (c) Use max_tokens to control response length and costs. (d) Store conversation history to maintain context across multiple messages.
Model Answer:
Supervised learning trains on labelled data — each training example has an input and a known correct output. The model learns to map inputs to outputs. Examples: email spam detection (label = spam/not spam), student pass prediction (label = passed/failed), house price prediction (label = actual price). Unsupervised learning trains on unlabelled data — there are no correct answers. The model finds patterns, structures and groupings by itself. Examples: customer segmentation (group similar customers), anomaly detection (find unusual transactions), topic modelling (discover themes in documents). The practical distinction: if you have historical data with outcomes and want to predict future outcomes — supervised. If you want to discover unknown patterns or structure in data — unsupervised. Semi-supervised learning uses a small amount of labelled data with a large amount of unlabelled data — common when labelling is expensive.
Model Answer:
Missing data in Pandas appears as NaN (Not a Number). Detection: df.isnull().sum() shows count of missing values per column; df.isnull().mean() shows percentage. Handling strategies: (1) Drop rows with missing values: df.dropna() — use when missing rows are few and random. (2) Drop columns: df.drop(columns=["col"]) — use when a column has >50% missing values. (3) Fill with a constant: df["col"].fillna(0) or fillna("Unknown") — use for categorical columns. (4) Fill with statistical measures: df["score"].fillna(df["score"].mean()) — use for numerical columns. (5) Forward/backward fill: df.fillna(method="ffill") — use for time series data. (6) Advanced imputation: use Scikit-learn's SimpleImputer or KNNImputer for sophisticated filling. Always understand WHY data is missing before deciding how to handle it — missing at random vs missing not at random have very different implications for model accuracy.
Model Answer:
Key certifications: (1) PCEP — Python Certified Entry-Level Programmer (Python Institute) — tests Python basics, syntax, data types, loops. Ideal starting point. (2) PCAP — Python Certified Associate in Programming — covers OOP, modules, exceptions, file handling. More advanced. (3) Google Professional Machine Learning Engineer (PMLE) — covers ML fundamentals, model development, MLOps, TensorFlow on Google Cloud. Very highly regarded. (4) AWS Machine Learning Specialty (MLS-C01) — ML on AWS using SageMaker, deep learning, data engineering. (5) Microsoft Azure AI Engineer (AI-102) — Azure AI services, computer vision, NLP, bot framework. (6) TensorFlow Developer Certificate — hands-on deep learning with TensorFlow. For a career in AI/Python in India, the recommended path is: PCAP → Google PMLE (or AWS ML Specialty) → specialise in a domain (NLP, computer vision, MLOps).
🏅 Certification Tip: For PCEP/PCAP exams focus on: data types, operators, string methods, list/dict operations, loops, functions, OOP basics and exception handling. For Google PMLE: ML workflow, model evaluation metrics (accuracy, precision, recall, F1), overfitting/underfitting, feature engineering and MLOps concepts.