Chapter 2: Python Programming for AI
Learning Outcomes
By the end of this chapter, students will be able to:
- Explain the basics of Python programming language and write programs with basic concepts of tokens
- Use selective and iterative statements effectively
- Gain practical knowledge on how to use libraries efficiently
Theory
Python Basics
Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.
Key Features
- Readability: Clean syntax with indentation-based blocks
- Versatility: Used in web development, data science, AI, and more
- Libraries: Extensive collection of libraries for various tasks
- Cross-platform: Runs on Windows, macOS, Linux, and more
Level 1: Basics of Python Programming
Character Sets and Tokens
- Character Set: Letters (A-Z, a-z), Digits (0-9), Special symbols (+, -, *, /, etc.)
- Tokens: The smallest unit of a program
- Keywords: Reserved words (if, else, for, while, def, class, etc.)
- Identifiers: Names given to variables, functions, classes
- Literals: Constant values (numbers, strings, booleans)
- Operators: Arithmetic, relational, logical, assignment
- Punctuators: Brackets, commas, colons, semicolons
Modes of Python
- Interactive Mode: Execute commands one at a time in Python shell
- Script Mode: Write complete programs in .py files and execute
Operators
# Arithmetic Operators
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Floor Division: 3
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000
# Relational Operators
print(a > b) # Greater than: True
print(a < b) # Less than: False
print(a == b) # Equal to: False
print(a != b) # Not equal to: True
# Logical Operators
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
Data Types
# Integer
age = 25
# Float
price = 19.99
# String
name = "Python"
# Boolean
is_active = True
# List (mutable sequence)
fruits = ["apple", "banana", "cherry"]
# Tuple (immutable sequence)
coordinates = (10, 20)
# Dictionary (key-value pairs)
student = {"name": "Alice", "age": 17}
# Set (unique elements)
unique_numbers = {1, 2, 3, 4, 5}
Control Statements
# Conditional Statements
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
# For Loop
for i in range(5):
print(i)
# While Loop
count = 0
while count < 5:
print(count)
count += 1
# Break and Continue
for num in range(10):
if num == 5:
break # Exit loop
if num == 2:
continue # Skip to next iteration
print(num)
Level 2: CSV Files and Libraries
Working with CSV Files
import csv
# Reading CSV file
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Writing to CSV file
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'Grade'])
writer.writerow(['Alice', 17, 'A'])
writer.writerow(['Bob', 18, 'B'])
NumPy Library
NumPy is a library for numerical computing with support for arrays and matrices.
import numpy as np
# Creating arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
# Array operations
print(arr1 + 10) # Add 10 to each element
print(arr1 * 2) # Multiply each element by 2
print(arr1.mean()) # Calculate mean
print(arr1.sum()) # Calculate sum
# Matrix operations
matrix = np.array([[1, 2], [3, 4]])
print(np.transpose(matrix)) # Transpose
print(np.linalg.det(matrix)) # Determinant
Pandas Library
Pandas is a library for data manipulation and analysis.
import pandas as pd
# Creating a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [17, 18, 16],
'Grade': ['A', 'B', 'A']
}
df = pd.DataFrame(data)
# Reading CSV file
df = pd.read_csv('students.csv')
# Basic operations
print(df.head()) # First 5 rows
print(df.describe()) # Statistical summary
print(df['Age'].mean()) # Mean of Age column
# Filtering data
filtered = df[df['Age'] > 16]
# Sorting data
sorted_df = df.sort_values('Age')
Scikit-learn Library
Scikit-learn is a library for machine learning.
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np
# Sample data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Create and train model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
predictions = model.predict(X_test)
Practical Activities
Activity 1: Python Basics (Level 1)
Write programs using operators, data types, and control statements:
Program 1: Calculator
def calculator():
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2 if num2 != 0 else "Error: Division by zero"
else:
result = "Invalid operator"
print(f"Result: {result}")
calculator()
Program 2: Prime Number Checker
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Program 3: Factorial Calculator
def factorial(n):
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
num = int(input("Enter a number: "))
print(f"Factorial of {num} is {factorial(num)}")
Activity 2: Libraries in AI (Level 2)
Write programs using NumPy, Pandas, and Scikit-learn:
Program 1: NumPy Array Operations
import numpy as np
# Create arrays
arr = np.array([10, 20, 30, 40, 50])
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Array statistics
print(f"Mean: {arr.mean()}")
print(f"Standard Deviation: {arr.std()}")
print(f"Sum: {arr.sum()}")
# Matrix operations
print(f"Matrix Transpose:\n{matrix.T}")
print(f"Matrix Sum: {matrix.sum()}")
Program 2: Pandas Data Analysis
import pandas as pd
# Create DataFrame
data = {
'Student': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
'Math': [85, 90, 78, 92, 88],
'Science': [88, 85, 82, 95, 90],
'English': [92, 80, 85, 88, 95]
}
df = pd.DataFrame(data)
# Analysis
print("First 3 rows:")
print(df.head(3))
print("\nStatistical Summary:")
print(df.describe())
print(f"\nAverage Math Score: {df['Math'].mean()}")
print(f"Highest Science Score: {df['Science'].max()}")
Competency-Based Questions
Example Questions
- Write a Python program to find the factorial of a number. (2 marks)
- Explain the difference between lists and tuples in Python. (3 marks)
- Write a function to check if a number is prime. (4 marks)
- Use NumPy to create a 3x3 matrix and perform matrix multiplication. (5 marks)
- Explain the role of Pandas in data analysis for AI projects. (6 marks)
Answers to Example Questions
-
Answer:
def factorial(n): if n == 0 or n == 1: return 1 result = 1 for i in range(2, n + 1): result *= i return result num = int(input("Enter a number: ")) print(f"Factorial of {num} is {factorial(num)}") -
Answer:
Feature List Tuple Mutability Mutable (can be changed) Immutable (cannot be changed) Syntax Square brackets []Parentheses ()Performance Slower Faster Use case When data needs modification When data should remain constant Example [1, 2, 3](1, 2, 3) -
Answer:
def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True number = int(input("Enter a number: ")) if is_prime(number): print(f"{number} is prime") else: print(f"{number} is not prime") -
Answer:
import numpy as np # Create two 3x3 matrices A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) # Matrix multiplication C = np.dot(A, B) # or A @ B print("Matrix A:\n", A) print("Matrix B:\n", B) print("A × B:\n", C) -
Answer: Pandas plays a crucial role in AI data analysis:
- Data Loading: Reads various formats (CSV, Excel, SQL, JSON)
- Data Cleaning: Handles missing values, duplicates, and outliers
- Data Transformation: Reshaping, merging, and aggregating data
- Exploration: Statistical summaries and data inspection with
describe(),info() - Feature Engineering: Creating new features for ML models
- Integration: Works seamlessly with NumPy, Scikit-learn, and visualization libraries
Official Sample Paper Questions
- What is the purpose of the NumPy library in Python? (2 marks)
- Write a Python program to sort a list of numbers in ascending order. (3 marks)
- Explain the difference between a list and a dictionary in Python. (4 marks)
- Use Pandas to read a CSV file and display the first five rows. (5 marks)
- Discuss the importance of Python in the field of artificial intelligence. (6 marks)
Answers to Official Sample Paper Questions
-
Answer: NumPy provides support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on them efficiently. It forms the foundation for scientific computing and AI in Python.
-
Answer:
numbers = [64, 34, 25, 12, 22, 11, 90] numbers.sort() # In-place sorting print("Sorted list:", numbers) # Or using sorted(): sorted_numbers = sorted(numbers) -
Answer:
Feature List Dictionary Structure Ordered sequence Key-value pairs Access By index By key Syntax [1, 2, 3]{'a': 1, 'b': 2}Order Maintains insertion order Maintains insertion order (Python 3.7+) Use Sequential data Associated data mapping -
Answer:
import pandas as pd # Read CSV file df = pd.read_csv('data.csv') # Display first five rows print(df.head()) -
Answer: Python is crucial for AI because:
- Simple Syntax: Easy to learn and read, faster prototyping
- Extensive Libraries: TensorFlow, PyTorch, Scikit-learn, Keras
- Data Handling: NumPy, Pandas for efficient data manipulation
- Community Support: Large community, extensive documentation
- Integration: Interfaces with C/C++ for performance-critical code
- Versatility: Suitable for research, development, and production
Practice Questions
Multiple Choice Questions
-
Which of the following is a mutable data type in Python? a) int b) float c) list d) tuple
-
What is the output of the following code?
print("Hello" + "World")a) HelloWorld b) Hello World c) Error d) None
-
Which library is used for numerical operations in Python? a) NumPy b) Pandas c) Matplotlib d) Scikit-learn
-
What does the
//operator do in Python? a) Regular division b) Floor division c) Modulus d) Exponentiation -
Which keyword is used to define a function in Python? a) function b) func c) def d) define
Short Answer Questions
- Define a variable in Python and provide an example.
- Explain the difference between a for loop and a while loop.
- What is the purpose of the Pandas library in Python?
- Write a Python program to calculate the sum of even numbers from 1 to 100.
Long Answer Questions
- Discuss the role of Python in artificial intelligence and machine learning.
- Explain the difference between lists and tuples in Python with examples.
- Write a Python program to read a CSV file and calculate the average of a specific column.
Summary
Key Points
- Python is a versatile programming language with simple syntax
- It supports multiple programming paradigms and has extensive libraries
- Python is widely used in AI for data processing, model training, and deployment
- Key libraries include NumPy for numerical operations, Pandas for data manipulation, and Scikit-learn for machine learning
Important Terminologies
- Token: Smallest unit of a program (keywords, identifiers, literals, operators)
- Variable: Container for storing data values
- Data Type: Classification of data (int, float, str, list, dict)
- Control Statement: Statements that control the flow of execution
- NumPy: Library for numerical computing with arrays
- Pandas: Library for data manipulation and analysis
- Scikit-learn: Library for machine learning algorithms
Solutions to Practice Questions
Multiple Choice Answers
- c) list
- a) HelloWorld
- a) NumPy
- b) Floor division
- c) def
Short Answer Model Answers
- A variable is a named storage location for data values. Example:
x = 10assigns the value 10 to variable x. - A for loop iterates over a sequence (like a list or range), while a while loop runs as long as a condition is true.
- Pandas is used for data manipulation and analysis, providing data structures like DataFrames for handling tabular data.
-
sum = 0 for i in range(1, 101): if i % 2 == 0: sum += i print(sum) # Output: 2550
Long Answer Model Answers
- Python’s simplicity, readability, and extensive libraries make it ideal for AI development. It enables rapid prototyping and deployment of machine learning models with libraries like TensorFlow, PyTorch, and Scikit-learn.
- Lists are mutable (can be changed after creation) and use square brackets [], while tuples are immutable (cannot be changed) and use parentheses (). Lists are better for collections that need modification; tuples are better for fixed collections.
-
import pandas as pd df = pd.read_csv('data.csv') average = df['column_name'].mean() print(f"Average: {average}")
IBM Skills Build Integration
Complete the IBM Skills Build - Python for Data Science course to:
- Gain hands-on experience with Python programming
- Learn to use NumPy, Pandas, and data visualization libraries
- Practice with real-world datasets
- Earn a certification to add to your portfolio
References
- CBSE Artificial Intelligence Curriculum for Class XI (2025-2026)
- IBM Skills Build - Python for Data Science
- Python Official Documentation (python.org)
- NumPy, Pandas, and Scikit-learn Documentation