Artificial Intelligence (AI) PYTHON
Artificial Intelligence (AI)
1. Introduction to Python
Python is an interpreted, high-level, general-purpose programming language. It was
created by Guido van Rossum and first released in 1991. Python is known for its
simplicity and readability, making it one of the most popular programming languages
today.
Easy to Read & Write: Python's syntax is straightforward and clean, making it easy for beginners.
• Versatile: Python is used in various fields like web development, data analysis, machine
learning, automation, and more.
• Large Community & Libraries: There are many libraries and frameworks available for
almost every need, like Flask for web apps, Pandas for data analysis, TensorFlow for
machine learning, etc.
Basic Syntax
Variables and Data Types
Python has dynamic typing, meaning you don’t need to declare a variable type explicitly.
x=5 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
print(x, y, name, is_active)
Comments
Use # for single-line comments.
# This is a comment
print("Hello, World!") # This is also a comment
ontrol Flow
If-Else Statements
Control the flow of your program with if, elif, and else.
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
Functions
Functions allow you to group code into reusable blocks.
def greet(name):
return f"Hello, {name}!"
result = greet("Alice")
print(result)
Lists
Lists are ordered collections that can hold a variety of data types.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Access first item
fruits.append("orange") # Add item
print(fruits)
. Dictionaries
Dictionaries store key-value pairs.
person = {"name": "Alice", "age": 25, "city": "Wonderland"}
print(person["name"]) # Access value by key
person["age"] = 26 # Modify value
print(person)
Classes and Objects (OOP)
Python supports Object-Oriented Programming (OOP) with classes and objects.
class Person:
def init (self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
person1 = Person("Alice", 25)
print(person1.introduce())
Exception Handling
Handle errors gracefully using try, except, and finally.
try:
x = 1 / 0 # This will cause an error
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This will always run.")
File Handling
Read and write files with Python.
# Write to a file
with open("example.txt", "w") as file:
file.write("Hello, file!")
# Read from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Modules and Libraries
Python has a rich ecosystem of libraries for different tasks, such as math, data manipulation,
web development, etc.
import math
print(math.sqrt(16)) # Square root of 16
List Comprehensions
A concise way to create lists in Python.
squares = [x**2 for x in range(5)]
print(squares)
Lambda Functions
Short anonymous functions
square = lambda x: x**2
print(square(4)) # Outputs: 16
Regular Expressions
Use the re module for pattern matching.
import re
text = "The rain in Spain"
pattern = r"\bS\w+" # Word starting with 'S'
matches = re.findall(pattern, text)
print(matches)
Numpy (For Data Science)
Python has many libraries for scientific computing, like NumPy for working with arrays.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2) # Multiply each element by 2
Pandas (For Data Science)
For data manipulation, pandas is an essential library.
import pandas as pd
# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [24, 27, 22]}
df = pd.DataFrame(data)
print(df)
Python Virtual Environments
A virtual environment is used to isolate your project’s dependencies.
python -m venv myenv
source myenv/bin/activate # On Unix/macOS
myenv\Scripts\activate # On Windows
Virtual Environment Folder Structure
Once created, the virtual environment folder (myenv) contains the following structure:
myenv/
├── bin/ # Contains the Python interpreter and scripts (Linux/macOS)
├── Include/ # Contains C headers (optional)
├── Lib/ # Contains Python libraries
├── Scripts/ # Contains the Python interpreter and scripts (Windows)
└── pyvenv.cfg # Configuration file for the virtual environment
Requests - HTTP Requests Library
The Requests library is a simple HTTP library for sending HTTP requests.
It's commonly used to interact with web APIs.
Pandas - Data Analysis and Manipulation
Pandas is a powerful library for data analysis and manipulation,
particularly with tabular data (e.g., CSV files).
import pandas as pd
# Creating a DataFrame from a dictionary
data = {
Name": ["Alice", "Bob", "Charlie"],
"Age": [24, 27, 22],
"City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
# Print the DataFrame
print(df)
# Perform a simple operation
average_age = df["Age"].mean()
print(f"Average Age: {average_age}")
NumPy - Numerical Computing
NumPy is used for working with arrays and performing complex mathematical operations.
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Perform mathematical operations on the array
arr_squared = arr ** 2
print("Squared Array:", arr_squared)
# Calculate the mean of the array
mean = np.mean(arr)
print("Mean:", mean)
Matplotlib - Data Visualization
Matplotlib is a library for creating static, animated, and interactive visualizations.
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# Create a simple line plot
plt.plot(x, y)
plt.title("Square Numbers Plot")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()
BeautifulSoup - Web Scraping
BeautifulSoup is a library for scraping web pages and extracting data from HTML and XML files.
import requests
from bs4 import BeautifulSoup
# Get the webpage content
url = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Find and print all the hyperlinks (anchor tags)
for link in soup.find_all('a'):
print(link.get('href'))
Flask - Web Development Framework
Flask is a micro web framework for building web applications.
from flask import Flask
app = Flask( name )
@app.route('/')
def home():
return "Hello, Flask!"
if name == ' main ':
app.run(debug=True)
Artificial Intelligence (AI)
Artificial Intelligence (AI) is the field of computer science that focuses on creating machines that can
perform tasks that typically require human intelligence.
These tasks include:
Learning from experience (like a student)
Understanding language (like Siri or ChatGPT)
Recognizing images (like facial recognition)
Making decisions (like a self-driving car)
Types of AI
Narrow AI (Weak AI)
Designed for one specific task
Examples: Google Translate, facial recognition, recommendation systems
General AI (Strong AI)
Can perform any intellectual task a human can do (still theoretical)
Superintelligent AI
Hypothetical future AI that surpasses human intelligence
Examples of AI in Daily Life
Voice assistants (Alexa, Siri)
Social media algorithms
Self-driving cars
Email spam filters
Chatbots and virtual customer service
Why AI Matters
Improves efficiency and productivity
Enables automation of repetitive tasks
Powers innovation in medicine, finance, transportation, and more
tep-by-step AI Code Example
1. Install required library
If you don’t already have it installed:
bash
Copy code
pip install scikit-learn
AI with Python Course Weekly schedule
Week 1: Basics of Python
● Python Installation
● What is Python
● Features of Python
● Variables
● Variable naming convention
● Data Types
● Variable Type Casting
● Input and Output
● Operators
● Keywords
● Conditional Statements(Types of operators, keywords, if, if-else, if-elif-else,
● Ternary expressions and match case)
● Loops in Python (for loop, while loop, nested loops, break, continue, pass)
● Functions in Python (def keyword, return statement, global & local variables,
recursion, lambda function, map function)
Week 2: Data Handling & Visualization
● Data Structures in Python (Lists, Tuples, Sets, Dictionaries)
● File Handling (File I/O: CSV and Error Handling in File I/O)
Introduction to Numpy (Numpy Arrays, Indexing, Slicing, Basic Numpy
operations, DataTypes in Numpy)
● Introduction to Pandas (DataFrames, Filtering, and Aggregations)
● Data Cleaning (Handling Missing values by deletion and imputation, Handling
● exact duplicates and fuzzy duplicate values)
● Data Visualisation Techniques (Introduction to Matplotlib library, seaborn library
and scikit-learn library)
Week 3: Data Analysis and Statistics for AI
● Covariance and Correlation
● Descriptive Statistics and Data Distribution (Measures of Central Tendency,
Measures of Dispersion, Measures of Shape, Data Distributions)
● Probability in AI (Basic Concepts of Probability, Types, Key Rules of Probability
and Applications of Probability in AI)
Week 4: Introduction to Machine Learning
● Introduction to Machine Learning
● Machine Learning Models (Supervised, Unsupervised and reinforcement learning,
Linear Regression, Logistic Regression, Decision Trees, Support Vector Machines,
K-Nearest Neighbors, Neural Networks, K-Means Clustering, Hierarchical
Clustering, Principal Component Analysis, Apriori Algorithm)
Week 5: ML Concepts
● Machine Learning Pipeline, Train and Test Data Split
● Evaluation Metrics for classification models and regression models
● Overfitting and Underfitting (Bias, Variance, Causes of Overfitting and
● Underfitting and strategies to prevent Overfitting and Underfitting)
● 2 Hands-On Mini Projects (House Sales price prediction and Loan Eligibility
prediction)
Week 6: Basics of Deep Learning
● Introduction to Deep Learning
● Neural Networks, Neurons
● Network Architecture, Forward and backward propagation
● Activation Functions, Types of Neural Networks
● Epochs, Splitting Datasets and Workflow
Week 7: Deep Learning Hands-On
● Normalisation, One-Hot Encoding
● Understanding Image Classification, Working with image datasets like MNIST,
Model Training and evaluation, Hands-on project to classify hand written digits
using Mnist Dataset.
Week 8: Real Time Project
● Introduction to Artificial Intelligence (What is AI, Core Concepts of AI, Branches
● of AI, AI Capabilities, Challenges and Ethical Considerations in AI, Real-Life
Examples of AI)
● Relationship between AI, ML, DL
● Final Hands-on project - Movie Recommendation System (Introduction on
use-case and Dataset, Data Preprocessing, NLP Techniques- TfidfVectorizer
● , Cosine Similarity, Developing a recommendation Model, Build a UI dropdown
for User Interaction)
WEBSITE – www.codeneksaLearning.cm
SUPPORT MAIL –
[email protected] CONTACT NO. – +91-9182029334