Advance Python

Published on June 29, 2025 by @mritxperts

A. Introduction to Python

Python is a high-level, easy-to-understand programming language. It is widely used in Artificial Intelligence and Machine Learning because of:

  • Simple syntax
  • Powerful libraries
  • Community support

In this unit, we move beyond basic Python and learn advanced Python concepts needed in AI projects.


B. Python Lists (Revision)

Definition:

A list is a collection of items enclosed in square brackets [].

Example:

pythonCopyEditfruits = ['apple', 'banana', 'orange']
print(fruits[0])  # Output: apple

List Operations:

  • append(): Add item to the end of the list
  • insert(index, value): Add item at specific index
  • remove(item): Remove first occurrence
  • pop(): Remove and return the last item

C. Python Dictionaries

Definition:

A dictionary is a collection of key-value pairs, enclosed in curly braces {}.

Example:

pythonCopyEditstudent = {
    'name': 'Ravi',
    'age': 15,
    'grade': '10th'
}
print(student['name'])  # Output: Ravi

Dictionary Methods:

  • keys() – returns all keys
  • values() – returns all values
  • get(key) – returns value of key
  • update() – updates dictionary

D. Python Functions

Definition:

A function is a block of code that performs a task and can be reused.

Creating a Function:

pythonCopyEditdef greet():
    print("Hello!")
greet()  # Output: Hello!

Function with Parameters:

pythonCopyEditdef add(a, b):
    return a + b
print(add(5, 3))  # Output: 8

E. Python Libraries in AI

Python uses libraries to make tasks easier. Libraries are collections of pre-written code.

Important AI Libraries:

LibraryUse
NumPyWorking with arrays, numerical operations
PandasWorking with data tables (DataFrames)
MatplotlibCreating graphs and charts
scikit-learnMachine Learning and model building

F. NumPy (Numerical Python)

Why Use NumPy?

  • Fast and memory-efficient
  • Helps with mathematical calculations on arrays

Creating an Array:

pythonCopyEditimport numpy as np

arr = np.array([1, 2, 3, 4])
print(arr[2])  # Output: 3

G. Pandas

Why Use Pandas?

  • Best for working with tabular data (like Excel files)
  • Helps with data cleaning, filtering, and exploring

Creating a DataFrame:

pythonCopyEditimport pandas as pd

data = {
    'Name': ['Amit', 'Neha'],
    'Marks': [90, 85]
}
df = pd.DataFrame(data)
print(df)

Important Pandas Operations:

  • df.head() – first 5 rows
  • df.describe() – summary stats
  • df['column'] – access specific column
  • df.loc[row] – access row by label

H. Matplotlib

Why Use It?

  • Used for drawing charts and graphs
  • Helps visualize data easily

Example – Bar Graph:

pythonCopyEditimport matplotlib.pyplot as plt

x = ['A', 'B', 'C']
y = [60, 70, 80]

plt.bar(x, y)
plt.title('Marks of Students')
plt.xlabel('Students')
plt.ylabel('Marks')
plt.show()

I. Conditional Statements

These are used to make decisions in code.

Syntax:

pythonCopyEditage = 18
if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible")

J. Loops

Used to repeat a block of code.

For Loop:

pythonCopyEditfor i in range(5):
    print(i)

While Loop:

pythonCopyEditcount = 0
while count < 3:
    print(count)
    count += 1

K. File Handling (Introduction)

We can read and write data from files.

Example:

pythonCopyEditfile = open("data.txt", "r")
print(file.read())
file.close()

L. Activity Suggestion

Activity:
Give students a CSV file with student names and marks.
Ask them to:

  • Load it using Pandas
  • Print the highest mark
  • Draw a bar graph using Matplotlib

M. Keywords to Remember

TermDescription
ListOrdered collection of items
DictionaryUnordered collection of key-value pairs
FunctionReusable block of code
LibraryPre-written code used to perform tasks
NumPyLibrary for numerical data
PandasLibrary for tabular data
MatplotlibLibrary for charts and graphs

N. Summary of the Unit

  • Python is a powerful tool used in AI projects.
  • We revised lists, dictionaries, functions, and learned about key libraries:
    • NumPy for arrays
    • Pandas for tables and datasets
    • Matplotlib for graphs
  • Understanding how to read, process, and visualize data using Python is essential for AI.