0% found this document useful (0 votes)
1 views53 pages

Learn to Code in Python_ From Basics to AI Integration

Uploaded by

Elayachi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views53 pages

Learn to Code in Python_ From Basics to AI Integration

Uploaded by

Elayachi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Learn to Code in Python:

From Basics to AI Integration


A Comprehensive Guide for Beginners
Course Overview

Course Modules Learning Objectives


1 Introduction to Python Programming check_circle Master Python fundamentals from basics to advanced
concepts
2 Python Basics
check_circle Learn to integrate AI into Python applications
3 Control Flow
check_circle Build practical AI-powered tools and applications
4 Data Structures
check_circle Develop skills in data analysis and visualization
5 Functions
check_circle Gain experience with real-world projects and exercises
6 Working with Files

7 AI Integration in Python

8 Data Analysis and Visualization

9 Web Scraping and APIs

10 Practical AI Projects
What is Python Programming?

history History & Overview


arrow_right Created byGuido van Rossumin 1991

arrow_right Named after the British comedy groupMonty Python

arrow_right Open-sourcewith a strong community

star Key Features


arrow_right Simple & readablesyntax

arrow_right Interpretedlanguage (no compilation needed)

arrow_right Cross-platformcompatibility

arrow_right Extensive librariesfor various applications "Python is an experiment in how much freedom
programmers need. Too much freedom and nobody can
read another's code; too little and expressiveness is
trending_up Why Python for AI? endangered."
arrow_right Rich ecosystem ofAI libraries(TensorFlow, PyTorch) - Guido van Rossum
arrow_right Excellentdata processingcapabilities

arrow_right Rapid prototypingand development


Setting Up Your Python Environment

download Installing Python laptop Setting Up Jupyter Notebooks


1 Visit python.org and download the latest version
2 Run the installer and check "Add Python to PATH"
3 Verify installation: open terminal and type python --version

code Your First Program


# This is your first Python program
print("Hello, World!")

Hello, World!

lightbulb The print() function displays text on the screen

1 Install using pip install jupyter


2 Launch with jupyter notebook command
3 Create a new notebook and start coding

build Alternative IDEs


arrow_rightVS Codewith Python extension
arrow_rightPyCharmfor professional development
arrow_rightGoogle Colabfor cloud-based coding
Writing and Running Python Code
code Python Syntax Basics compare Scripts vs. Interactive Environments
arrow_right No semicolonsneeded at end of lines
Scripts (.py files) Interactive (Jupyter)
arrow_right Indentationdefines code blocks
Complete programs Cell-based execution
arrow_right Commentsstart with # symbol
Run from command line Run individual cells

calculate Basic Calculations Better for large projects Better for experimentation

# Basic arithmetic operations Text editor or IDE Web-based interface


addition = 5 + 3
subtraction = 10 - 4
multiplication = 6 * 7
division = 15 / 3 play_circle Executing Python Code
exponent = 2 ** 3
# In a script file (example.py)
print(addition)
name = "Python Learner"
print(multiplication)
greeting = "Hello, " + name
print(greeting)
8
42
Hello, Python Learner

lightbulb Run scripts with python example.py in terminal


Data Types in Python

text_fields Strings exposure_zero Integers


Text data enclosed in quotes (single or double). Used for storing Whole numbers (positive, negative, or zero) without decimal
and manipulating text. points. Used for counting and indexing.

name = "Python"
message = 'Hello, World!' age = 25
multi_line = """This is a temperature = -5
multi-line string""" count = 1000000

type(name) → <class 'str'> type(age) → <class 'int'>

functions Floats toggle_on Booleans


Numbers with decimal points. Used for precise calculations, Represents one of two values: True or False. Used for logical
measurements, and scientific computations. operations and conditional statements.

pi = 3.14159 is_active = True


price = 19.99 has_permission = False
scientific = 1.5e2 # 150.0 result = 5 > 3 # True

type(pi) → <class 'float'> type(is_active) → <class 'bool'>


Variables and Assignment
save Creating Variables text_format Naming Conventions
arrow_right Variables storedata values
Rule Examples
arrow_right Created usingassignment operator(=)
Use lowercase letters my_variable user_name
arrow_right Nodeclarationneeded before use

Use underscores for spaces first_name total_price


# Variable assignment examples
name = "Python"
age = 30 Start with letter or underscore _private data1
price = 19.99
is_active = True
Avoid Python keywords class_ function_

category Checking Variable Types


sync Variable Reassignment
# Using type() function
print(type(name)) # Variables can be reassigned
print(type(age)) x = 10
print(type(price)) print("x =", x)
print(type(is_active))
x = "Hello"
print("x =", x)
<class 'str'>
<class 'int'> # Multiple assignment
<class 'float'> a, b, c = 1, 2, 3
<class 'bool'>
x = 10
x = Hello

lightbulb Python is dynamically typed - variable types can change


Basic Operations and Calculations

calculate Arithmetic Operators compare_arrows Comparison Operators call_split Logical Operators


+ - * / % ** // == != < > <= >= and or not

Examples: Examples: Examples:

a = 10 x = 5 p = True
b = 3 y = 10 q = False

addition = a + b equal = x == y and_result = p and q


subtraction = a - b not_equal = x != y or_result = p or q
multiplication = a * b less_than = x < y not_p = not p
division = a / b greater_than = x > y not_q = not q
modulus = a % b less_equal = x <= y
exponent = a ** b greater_equal = x >= y # Combined example
floor_div = a // b age = 25
equal = False has_id = True
addition = 13 not_equal = True can_vote = age >= 18 and has_id
subtraction = 7 less_than = True
multiplication = 30 greater_than = False and_result = False
division = 3.333... less_equal = True or_result = True
modulus = 1 greater_equal = False not_p = False
exponent = 1000 not_q = True
floor_div = 3 can_vote = True
Conditional Statements
call_split Basic Conditional Structure layers Nested Conditionals
arrow_right if: Executes code if condition is True
# Validating user input
arrow_right elif: Checks additional conditions username = input("Enter username: ")
password = input("Enter password: ")
arrow_right else: Executes if all conditions are False
if username == "admin":
if password == "secret123":
print("Access granted")
Start else:
print("Wrong password")
else:
if condition?
print("Unknown user")

Execute code block

check_circle Practical Application


Continue
# Data validation example
temperature = float(input("Enter temperature:
"))

code Simple Example if temperature < -273.15:


print("Invalid: Below absolute zero")
elif temperature < 0:
# Checking user age print("Freezing temperatures")
age = 18 elif temperature < 100:
print("Normal range")
if age >= 18: else:
print("You can vote") print("Boiling point exceeded")
elif age >= 16:
print("You can drive")
else:
print("You're too young") lightbulb Use indentation to define code blocks within conditions

You can vote


Loops in Python

loop Loop Types autorenew While Loop Examples


# Basic while loop
repeat For Loops autorenew While Loops count = 0
arrow_right Iterate oversequences arrow_right Execute conditionis while count < 5:
while True print(count)
arrow_right Knownnumberof count += 1
iterations arrow_right Unknownnumber of
iterations 0
1
2
3
4
repeat For Loop Examples
# Iterating over a list control_point Loop Control Statements
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # Using break and continue
for i in range(10):
# Using range() function if i == 3:
for i in range(5): continue # Skip to next iteration
print(i) if i == 7:
break # Exit the loop
print(i)
apple
banana
cherry 0
0 1
1 2
2 4
3 5
4 6

break exits the loop entirely


lightbulb
continue skips to the next iteration
Practical Applications and Exercises

apps Real-World Applications assignment Practice Exercises

input Input Validation calculate Data Processing Exercise 1: Number Classifier Easy

username = numbers = [12, 7, Write a program that asks for a number and classifies it as:
input("Enter 15, 3, 9]
username: ") total = 0 arrow_right Positiveif greater than 0
if len(username) < for num in
3: numbers: arrow_right Negativeif less than 0
print("Too if num > 10:
short") total += arrow_right Zeroif equal to 0
elif len(username) num
> 20: print("Sum of
print("Too numbers > 10:",
long") total)
else: Exercise 2: Prime Number Checker Medium
print("Valid
username") Create a program that checks if a given number is prime:

arrow_right Use aloopto test divisibility

arrow_right Useconditionalstatements to check


casino Simple Game security Password Checker arrow_right Print appropriate message
import random password =
secret = input("Password:
random.randint(1, ")
10) has_upper = False Exercise 3: Number Guessing Game Hard
guess = 0 has_digit = False
while guess != for char in Build an interactive number guessing game:
secret: password:
guess = if arrow_right Generate arandomnumber between 1-100
int(input("Guess: char.isupper():
")) has_upper arrow_right Allowlimitednumber of guesses
if guess < = True
secret: if arrow_right Providehints(higher/lower)
print("Too char.isdigit():
low") has_digit arrow_right Track and displayscore
print("Correct!") = True
Lists in Python
format_list_bulleted Creating and Accessing Lists build Common List Methods
arrow_right Orderedcollection of items
add append() insert insert()
arrow_right Mutable- can be changed after creation
Adds item to the end of list Inserts item at specified
arrow_right Can containmixed data types position

# Creating lists
empty_list = [] remove remove() sort sort()
numbers = [1, 2, 3, 4, 5]
Removes first occurrence of Sorts list in ascending order
mixed = [1, "hello", 3.14, True]
value
# Accessing elements
first = numbers[0] # 1
last = numbers[-1] # 5 # Using list methods
subset = numbers[1:3] # [2, 3] numbers = [3, 1, 4, 1, 5]
numbers.append(9) # [3, 1, 4, 1, 5, 9]
numbers.insert(2, 2) # [3, 1, 2, 4, 1, 5, 9]
numbers.remove(1) # [3, 2, 4, 1, 5, 9]
loop Iterating Over Lists numbers.sort() # [1, 2, 3, 4, 5, 9]

# Using for loop


fruits = ["apple", "banana", "cherry"]
for fruit in fruits: auto_awesome List Comprehensions
print(fruit)
# Traditional approach
# Using enumerate() for index and value squares = []
for index, fruit in enumerate(fruits): for x in range(10):
print(f"{index}: {fruit}") squares.append(x**2)

# Using list comprehension


apple squares = [x**2 for x in range(10)]
banana
cherry # With condition
0: apple even_squares = [x**2 for x in range(10) if x %
1: banana 2 == 0]
2: cherry

psychology AI Applications

data_array Data Processing


Storing and manipulating datasets for machine learning

memory Feature Vectors


Representing features of data points in AI models
Dictionaries in Python
account_tree Creating and Accessing Dictionaries build Common Dictionary Methods
arrow_right Key-valuepairs
key keys() data_array values()
arrow_right Unorderedcollection
Returns all keys in dictionary Returns all values in dictionary
arrow_right Mutable- can be changed after creation

arrow_right Keys must beuniqueandimmutable


list items() update update()
Returns key-value pairs as Updates dictionary with
# Creating dictionaries
empty_dict = {} tuples another dict
person = {"name": "John", "age": 30}

# Accessing values # Using dictionary methods


name = person["name"] # "John" student = {"name": "Alice", "grade": "A"}
age = person.get("age") # 30 keys = student.keys() # dict_keys(['name',
'grade'])
# Adding/updating items values = student.values() #
person["city"] = "New York" dict_values(['Alice', 'A'])
person["age"] = 31 items = student.items() # dict_items([('name',
'Alice'), ('grade', 'A')])

# Update with another dictionary


loop Iterating Over Dictionaries student.update({"age": 20, "grade": "A+"})

# Iterating over keys


for key in person:
print(key) auto_awesome Dictionary Comprehensions
# Iterating over values # Traditional approach
for value in person.values(): squares = {}
print(value) for x in range(5):
squares[x] = x**2
# Iterating over key-value pairs
for key, value in person.items(): # Using dictionary comprehension
print(f"{key}: {value}") squares = {x: x**2 for x in range(5)}

# With condition
name even_squares = {x: x**2 for x in range(10) if
age x % 2 == 0}
city
John
31
New York
name: John psychology AI Applications
age: 31
city: New York
settings Model Configuration
Storing hyperparameters for AI models

category Feature Mapping


Mapping feature names to their values or indices
Other Data Structures and Applications

category Additional Data Structures psychology AI Applications

dataset Dataset Storage


filter_1 Tuples filter_none Sets
# Using lists for dataset features
arrow_right Immutablesequences arrow_right Unorderedcollections features = [
[5.1, 3.5, 1.4, 0.2], # Sample 1
arrow_right Defined parentheses arrow_right Uniqueelements only [4.9, 3.0, 1.4, 0.2], # Sample 2
with [7.0, 3.2, 4.7, 1.4] # Sample 3
arrow_right Defined withcurly braces ]
arrow_right Fasterthan lists
# Creating sets # Using dictionaries for labeled data
# Creating tuples unique_numbers = {1, sample = {
coordinates = 2, 3, 2, 1} "features": [5.1, 3.5, 1.4, 0.2],
(10, 20) vowels = {'a', 'e', "label": "setosa"
rgb = ("red", 'i', 'o', 'u'} }
"green", "blue")
# Set operations
# Accessing print(unique_numbers)
elements # {1, 2, 3}
x = vowels.add('y') # Add settings Model Parameters
coordinates[0] # element
10 vowels.remove('a') # # Using tuples for fixed parameters
Remove element model_config = (
# Tuples are "neural_network", # Model type
immutable 128, # Hidden units
# coordinates[0] 0.001, # Learning rate
= 15 # Error! 50 # Epochs
)

# Using dictionaries for hyperparameters


hyperparams = {
"learning_rate": 0.001,
"batch_size": 32,
"epochs": 50
}

memory Feature Vectors

# Using sets for unique features


unique_features = {
"color", "shape", "size",
"texture", "weight"
}

# Using lists for ordered embeddings


word_embedding = [
0.21, -0.45, 0.67, 0.12,
-0.33, 0.78, -0.56, 0.91
]
Introduction to Functions
functions What are Functions? Functions that Return
arrow_return
arrow_right Reusableblocks of code Values
arrow_right Performspecific tasks # Function with return value
def add_numbers(a, b):
arrow_right Promotecode organization result = a + b
return result
arrow_right Enablecode reuseand modularity
# Using the returned value
sum_result = add_numbers(5, 3)
code Defining and Calling Functions print(f"Sum: {sum_result}")

# Function definition
def greet(): Sum: 8
print("Hello, World!")

# Function call public Function Scope


greet()
# Global variable
global_var = "I'm global"
Hello, World!
def show_scope():
# Local variable
input Functions with Parameters local_var = "I'm local"
print(global_var)
# Function with parameters print(local_var)
def greet_person(name):
print(f"Hello, {name}!") show_scope()
print(global_var)
# Calling with arguments # print(local_var) # This would cause an error
greet_person("Alice")
greet_person("Bob")
I'm global
I'm local
Hello, Alice! I'm global
Hello, Bob!
Local variables only exist within the function
lightbulb
Global variables can be accessed anywhere
Function Parameters and Arguments
tune Types of Parameters settings Default & Variable-length Parameters
# Default parameters
filter_1 Positional filter_2 Keyword
def greet(name, greeting="Hello"):
Required parameters in Identified by parameter name print(f"{greeting}, {name}!")
specific order
greet("Alice") # Uses default
greet("Bob", "Hi there") # Overrides default
filter_3 Default filter_4 Variable-length # Variable-length parameters
Have predefined values Accept any number of def sum_all(*args):
arguments total = 0
for num in args:
total += num
return total

code Positional & Keyword Parameters print(sum_all(1, 2, 3)) # 6


print(sum_all(10, 20, 30, 40)) # 100
# Positional parameters
def describe_person(name, age):
print(f"{name} is {age} years old")
layers **kwargs and Parameter Passing
# Calling with positional arguments
describe_person("Alice", 30)
# **kwargs for keyword arguments
# Calling with keyword arguments def display_info(**kwargs):
describe_person(name="Bob", age=25) for key, value in kwargs.items():
describe_person(age=35, name="Charlie") print(f"{key}: {value}")

display_info(name="Alice", age=30, city="NY")


Alice is 30 years old
Bob is 25 years old # Parameter passing by assignment
Charlie is 35 years old def modify_list(my_list):
my_list.append(4) # Modifies original

numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # [1, 2, 3, 4]

*args collects positional arguments into a tuple


lightbulb
**kwargs collects keyword arguments into a dictionary
Advanced Function Concepts

auto_awesome Advanced Function Types psychology AI Applications

functions Lambda Functions loop Recursion transform Data Preprocessing


Anonymous functions Functions that call themselves # Lambda for data transformation
normalize = lambda x: (x - min(x)) / (max(x)
# Traditional # Factorial with - min(x))
function recursion
def square(x): def factorial(n): # Function for feature scaling
return x ** 2 if n == 0: def standardize_features(data):
return 1 mean = sum(data) / len(data)
# Lambda else: std = (sum((x - mean)**2 for x in data)
equivalent return n * / len(data))**0.5
square = lambda factorial(n-1) return [(x - mean) / std for x in data]
x: x ** 2
print(factorial(5))
# Common use case # 120
numbers = [1, 2,
3, 4, 5]
squared = construction Feature Engineering
list(map(lambda
# Function to create polynomial features
x: x**2,
def create_polynomial_features(X, degree=2):
numbers))
features = [X]
for d in range(2, degree+1):
features.append([x**d for x in X])
return features

# Recursive feature selection


extension Function Decorators def select_features(features, target, n):
if n <= 0 or not features:
# Creating a decorator return []
def timer(func): best = find_best_feature(features,
def wrapper(*args, **kwargs): target)
import time remaining = [f for f in features if f !=
start = time.time() best]
result = func(*args, **kwargs) return [best] +
end = time.time() select_features(remaining, target, n-1)
print(f"Execution time: {end-
start:.5f}s")
return result
return wrapper
analytics Model Evaluation
# Using the decorator
@timer # Decorator for model evaluation
def slow_function(): def evaluate_model(func):
import time def wrapper(X, y, *args, **kwargs):
time.sleep(1) from sklearn.metrics import
return "Done" accuracy_score
predictions = func(X, *args,
**kwargs)
accuracy = accuracy_score(y,
predictions)
print(f"Model accuracy:
{accuracy:.4f}")
return predictions
return wrapper

Advanced functions enable flexible and reusable code for


lightbulb
AI applications
Reading and Writing Text Files
description File Handling Basics code Reading Files
arrow_right open()function to access files
# Reading entire file
arrow_right Specifyfile mode(r, w, a, r+) with open("data.txt", "r") as file:
content = file.read()
arrow_right Alwaysclose()files when done print(content)

# Reading line by line


# Basic file operations with open("data.txt", "r") as file:
file = open("example.txt", "r") # Open for
for line in file:
reading
print(line.strip()) # Remove newline
content = file.read() # Read entire file
file.close() # Close the file
# Reading all lines into a list
with open("data.txt", "r") as file:
lines = file.readlines()

settings File Modes

visibility Read ('r') edit Write ('w') create Writing Files


Default mode for reading files Overwrites existing content
# Writing to a file (overwrites)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
add Append ('a') sync Read/Write ('r+') file.write("This is a new file.\n")
Adds to end of file Both reading and writing
# Appending to a file
with open("output.txt", "a") as file:
file.write("This line is appended.\n")

# Writing multiple lines


lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)

lightbulb Use with statement for automatic file closing


Working with CSV and Structured Data

table_chart CSV Files data_object JSON Data


arrow_right Comma-Separated Valuesformat arrow_right JavaScript Object Notation

arrow_right Common fortabular data arrow_right Common forweb APIs

arrow_right Built-incsvmodule for handling arrow_right Built-injsonmodule for handling

# Reading CSV files # Reading JSON data


import csv import json

with open('data.csv', 'r') as file: with open('data.json', 'r') as file:


reader = csv.reader(file) data = json.load(file)
for row in reader: print(data['key']) # Access values
print(row) # Each row is a list
# Writing JSON data
# Writing CSV files data = {'name': 'Alice', 'age': 30, 'hobbies':
data = [['Name', 'Age'], ['Alice', 30], ['reading', 'coding']}
['Bob', 25]] with open('output.json', 'w') as file:
with open('output.csv', 'w', newline='') as json.dump(data, file, indent=4) # Pretty
file: print
writer = csv.writer(file)
writer.writerows(data)

psychology AI Applications
code Advanced CSV Handling
dataset Dataset Loading settings Configuration Files
# Using DictReader for named columns CSV files for training data JSON for model parameters
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader: # Example: Loading AI dataset from CSV
print(row['Name'], row['Age']) import csv
# Using DictWriter to write with headers features = []
fieldnames = ['Name', 'Age', 'City'] labels = []
with open('output.csv', 'w', newline='') as
file: with open('dataset.csv', 'r') as file:
writer = csv.DictWriter(file, reader = csv.DictReader(file)
fieldnames=fieldnames) for row in reader:
writer.writeheader() features.append([float(row['f1']),
writer.writerow({'Name': 'Charlie', 'Age': float(row['f2'])])
35, 'City': 'NY'}) labels.append(int(row['label']))

lightbulb Structured data formats are essential for AI data pipelines


Practical Applications of File Handling

 Data Preprocessing  Log File Analysis

import csv error_counts = {}


with open('server.log', 'r') as file:
cleaned_data = [] for line in file:
with open('raw_data.csv', 'r') as file: if 'ERROR' in line:
reader = csv.DictReader(file) error_type = line.split(':')[1]
for row in reader: error_counts[error_type] =
if row['value'] != 'NA': error_counts.get(error_type, 0) + 1
cleaned_data.append(row)
 Pattern Detection  Statistics  Error Tracking
 Cleaning  Filtering  Transforming

 Report Generation  AI Data Preparation

with open('report.txt', 'w') as report: import json


report.write("Data Analysis Report\n")
report.write("====================\n\n") training_data = []
report.write(f"Total records: {total_records}\n") with open('reviews.json', 'r') as file:
report.write(f"Average value: {avg_value:.2f}\n") reviews = json.load(file)
for review in reviews:
 Automation  Formatting  Exporting training_data.append({
'text': review['content'],
'label': review['sentiment']
})

 ML Training  Labeling  Feature Engineering

 Key Insight: Effective file handling is essential for building robust data pipelines that power AI applications
File Handling Exercises

Easy
CSV Data Processor
Create a program that processes student data from a CSV file:

 Read a CSV file with student data


 Calculate the average grade for each student
 Write results to a new CSV file with calculated averages

Medium
JSON Configuration Manager
Build a configuration manager that handles JSON files:

 Load settings from a JSON file


 Allow updating specific configuration values
 Save changes back to the file with proper validation

Hard
Data Pipeline Builder
Develop a data processing pipeline that:

 Read data from multiple sources (CSV, JSON, TXT)


 Transform and clean the data
 Generate a consolidated report in multiple formats
 Implement proper error handling throughout the pipeline

 Remember: Always use context managers (with statements) for file operations to ensure proper resource management and error handling.
Introduction to AI Libraries in Python

psychology Why Python for AI?


Python is the preferred language for AI development due to its simplicity, extensive libraries, and strong community support. Its readable
syntax and rich ecosystem make it ideal for both beginners and experts in AI.

memory TensorFlow whatshot PyTorch


arrow_right Open-sourceby Google arrow_right Dynamiccomputation graphs

arrow_right Excellent fordeep learning arrow_right MorePythonicinterface

arrow_right Strongproductiondeployment arrow_right Preferred inresearchcommunity

arrow_right Supportsdistributed computing arrow_right Excellentdebuggingcapabilities

Image Recognition NLP Time Series Computer Vision Reinforcement Learning GANs

scatter_plot Scikit-learn layers Keras


arrow_right Traditionalmachine learning arrow_right High-levelneural networks API

arrow_right Simple andconsistent API arrow_right Runs on top ofTensorFlow

arrow_right Greatdocumentation arrow_right User-friendlyinterface

arrow_right Built onNumPyand SciPy arrow_right Modularand extensible

Classification Regression Clustering Rapid Prototyping Beginner-friendly Research


Integrating AI into Python Applications

integration_instructions Integration Approaches translate Natural Language Processing


arrow_right Pre-trained models- Leverage existing AI
# Using Hugging Face Transformers for NLP
arrow_right API calls- Connect to cloud AI services from transformers import pipeline

arrow_right Custom implementations- Build from scratch # Create a text classification pipeline
classifier = pipeline('sentiment-analysis')

# Analyze text sentiment


image Image Recognition Example result = classifier("I love learning Python
for AI!")
# Using TensorFlow for image classification print(result)
import tensorflow as tf # Output: [{'label': 'POSITIVE', 'score':
from tensorflow.keras.applications import 0.9998}]
MobileNetV2
from tensorflow.keras.preprocessing import # Text generation with GPT-style model
image generator = pipeline('text-generation',
model='gpt2')
# Load pre-trained model output = generator("Python is great for",
model = MobileNetV2(weights='imagenet') max_length=20)

# Prepare and classify image


img_path = 'example.jpg'
img = image.load_img(img_path, target_size= api API Integration Example
(224, 224))
img_array = image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Using OpenAI API for advanced AI tasks
predictions = model.predict(img_array) import openai

# Set API key


openai.api_key = 'your-api-key'

# Generate text with GPT-3/4


response = openai.Completion.create(
engine="text-davinci-003",
prompt="Write a Python function to
calculate factorial",
max_tokens=150
)

print(response.choices[0].text.strip())

AI integration allows Python applications to leverage powerful


lightbulb
models without building them from scratch
Using Python for AI Development
timeline AI Development Lifecycle psychology Neural Networks with Python
arrow_right Data preprocessing- Clean and prepare data
# Building a simple neural network with Keras
arrow_right Feature engineering- Extract meaningful features import tensorflow as tf
from tensorflow.keras.models import Sequential
arrow_right Model training- Build and train AI models from tensorflow.keras.layers import Dense

arrow_right Evaluation- Test model performance # Create model


model = Sequential([
arrow_right Deployment- Integrate into applications Dense(64, activation='relu', input_shape=
(4,)),
Dense(32, activation='relu'),
model_training Simple Machine Learning Model ])
Dense(3, activation='softmax')

# Using scikit-learn for classification # Compile and train


from sklearn.datasets import load_iris model.compile(optimizer='adam',
from sklearn.model_selection import loss='sparse_categorical_crossentropy',
train_test_split metrics=['accuracy'])
from sklearn.ensemble import model.fit(X_train, y_train, epochs=10)
RandomForestClassifier
from sklearn.metrics import accuracy_score

# Load dataset
iris = load_iris() analytics Model Evaluation & Deployment
X, y = iris.data, iris.target
# Evaluate model performance
# Split data y_pred = model.predict(X_test)
X_train, X_test, y_train, y_test = y_pred_classes = tf.argmax(y_pred, axis=1)
train_test_split( accuracy = accuracy_score(y_test,
X, y, test_size=0.2, random_state=42 y_pred_classes)
) print(f"Model accuracy: {accuracy:.4f}")

# Save model for deployment


model.save('iris_classifier.h5')

# Load and use the model


loaded_model =
tf.keras.models.load_model('iris_classifier.h5')
predictions = loaded_model.predict(X_test)

Python's versatility makes it ideal for the entire AI development


lightbulb
pipeline
Practical AI Integration Projects

apps AI-Powered Project Ideas code Building a Recipe Generator


# Step 1: Define function with AI
restaurant_menu Custom Recipe Generator checklist Smart To-Do List integration
def generate_recipe(ingredients,
arrow_right Ingredientsinput arrow_right AI- prioritization dietary_restrictions=None):
powered # Format ingredients for prompt
arrow_right AI-generatedrecipes ingredients_str = ",
arrow_right Smartscheduling ".join(ingredients)

# Create AI prompt
prompt = f"Create a recipe using:
Dream Vacation {ingredients_str}"
travel_explore Travel Blog Analyzer flight Planner
arrow_right Extractkey information if dietary_restrictions:
arrow_right Personalizeditineraries prompt += f" that is
arrow_right Restaurantrecommendations {dietary_restrictions}"
arrow_right Activitysuggestions
# Call AI API (example using OpenAI)
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=300
)

return response.choices[0].text.strip()

# Step 2: Create user interface


def recipe_generator_app():
print("Welcome to AI Recipe
Generator!")
ingredients = input("Enter ingredients
(comma separated): ")
ingredients_list = [i.strip() for i in
ingredients.split(",")]

dietary = input("Any dietary


restrictions? (optional): ")

recipe =
generate_recipe(ingredients_list, dietary)
print("\nHere's your recipe:\n")
print(recipe)

Extension ideas: Add ingredient substitution suggestions,


lightbulb
cooking time estimates, or nutritional information
Introduction to Data Analysis with Python
analytics Key Data Analysis Libraries transform Data Manipulation
# Selecting columns
table_chart Pandas grid_on NumPy functions SciPy subset = df[['column1',
'column2']]
arrow_right DataFrames arrow_right Arrays arrow_right Scientificcomputing
# Filtering data
arrow_right Datamanipulation arrow_right Mathematicaloperations arrow_right Statisticalfunctions filtered = df[df['column'] >
100]

# Grouping and aggregation


grouped =
dataset Loading and Cleaning Data df.groupby('category')
['value'].mean()
# Import libraries
import pandas as pd # Creating new columns
import numpy as np df['new_column'] = df['col1']
+ df['col2']
# Load data from CSV
df = pd.read_csv('data.csv') # Applying functions
df['processed'] =
# Inspect data df['text'].str.lower()
print(df.head()) # First 5 rows
print(df.info()) # Data types & non-null counts

# Handle missing values bar_chart Statistical Analysis


df_clean = df.dropna() # Drop rows with missing values
df_filled = df.fillna(0) # Fill with 0
# Basic statistics
print(df.describe()) #
Summary statistics

# Correlation analysis
correlation = df.corr()

# Using NumPy for


calculations
values = df['column'].values
mean_val = np.mean(values)
std_val = np.std(values)

# Using SciPy for statistical


tests
from scipy import stats
t_stat, p_val =
stats.ttest_ind(df['group1'],
df['group2'])

Data analysis libraries are essential


lightbulb
for AI applications, providing tools for
data preprocessing, exploration, and
feature engineering
Data Visualization with Python

bar_chart Visualization Libraries scatter_plot Advanced Visualizations


# Scatter plot with seaborn
insert_chart Matplotlib palette Seaborn 3d_rotation Plotly tips = sns.load_dataset('tips')
sns.scatterplot(x='total_bill',
arrow_right Foundationlibrary arrow_right Statisticalplots arrow_right Interactiveplots y='tip', data=tips)
plt.title('Tips vs Total Bill')
arrow_right Highlycustomizable arrow_right Beautifuldefaults arrow_right Web- visualizations plt.show()
based
# Histogram
plt.hist(tips['total_bill'],
bins=10)
plt.title('Distribution of Total
code Creating Basic Plots Bills')
plt.show()
# Import libraries
# Box plot
import matplotlib.pyplot as plt
sns.boxplot(x='day',
import seaborn as sns
y='total_bill', data=tips)
import pandas as pd
plt.title('Total Bill by Day')
plt.show()
# Line plot
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title('Simple Line Plot') Line Bar Scatter Histogram Box
plt.show()
Heatmap Violin
# Bar chart
plt.bar(['A', 'B', 'C'], [3, 7, 2])
plt.title('Simple Bar Chart')
plt.show()
insights Visualization in AI
arrow_right Data exploration- Understand patterns
arrow_right Feature analysis- Identify relationships
arrow_right Model evaluation- Compare performance
arrow_right Result communication- Present findings
Effective visualization is crucial for
lightbulb
understanding data patterns and
communicating AI results
Practical Data Analysis and Visualization Projects

insights Project Ideas code Step-by-Step Example: Sales Analysis


# Step 1: Load and explore data
trending_up Sales Analysis public Social Media Trends import pandas as pd
import matplotlib.pyplot as plt
arrow_right Trendidentification arrow_right Sentimentanalysis import seaborn as sns

arrow_right Seasonalpatterns arrow_right Engagementmetrics # Load dataset


df = pd.read_csv('sales_data.csv')
print(df.head())
print(df.info())
dataset Dataset Exploration wb_sunny Weather Patterns
arrow_right Featureengineering arrow_right Time seriesanalysis # Step 2: Data cleaning and preprocessing
# Handle missing values
arrow_right Correlationanalysis arrow_right Forecastingmodels df = df.dropna()

# Convert date column to datetime


df['date'] = pd.to_datetime(df['date'])

# Extract month and year


df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year

# Step 3: Analysis and visualization


# Monthly sales trend
monthly_sales = df.groupby('month')
['sales'].sum()
plt.figure(figsize=(10, 6))
monthly_sales.plot(kind='bar')
plt.title('Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Total Sales')
plt.show()

Extension ideas: Add product category analysis, customer


lightbulb
segmentation, or predictive forecasting
Introduction to Web Scraping with Python

language Web Scraping Libraries data_object Extracting Different Elements


# Extract all links
soup_kitchen BeautifulSoup spider
Scrapy links = soup.find_all('a')
for link in links[:5]: # First 5 links
arrow_right HTML/XMLparsing arrow_right Fullscraping framework print(link.get('href'))

arrow_right Simplesyntax arrow_right Asynchronousprocessing # Extract text from paragraphs


paragraphs = soup.find_all('p')
for p in paragraphs[:2]: # First 2 paragraphs
print(p.text.strip())

code Basic Web Scraping Example # Extract table data


table = soup.find('table')
# Import required libraries if table:
import requests rows = table.find_all('tr')
from bs4 import BeautifulSoup for row in rows[:3]: # First 3 rows
cells = row.find_all('td')
# Send HTTP request row_data = [cell.text for cell in
url = "https://example.com" cells]
response = requests.get(url) print(row_data)

# Parse HTML content


soup = BeautifulSoup(response.text,
'html.parser') gavel Ethical & Legal Considerations
# Extract page title arrow_right Check website'srobots.txtfile
title = soup.find('title').text
print(f"Page title: {title}") arrow_right ReviewTerms of Service
arrow_right Respectcopyrightlaws
arrow_right Don't overload servers withtoo many requests
Web scraping provides valuable data for AI applications like
lightbulb
training datasets, market analysis, and trend prediction
Working with APIs in Python

api API Fundamentals data_object Common API Use Cases


arrow_right APIsallow software applications to communicate
wb_sunny Weather Data trending_up Financial Data
arrow_right RESTfulAPIs use HTTP methods (GET, POST, PUT, DELETE)
arrow_right Data typically exchanged inJSONor XML format arrow_right Real-timeforecasts arrow_right Stockprices
arrow_right Authenticationoften required (API keys, OAuth) arrow_right Historicalpatterns arrow_right Markettrends

code Making HTTP Requests


public Social Media psychology AI Services
# Import requests library
import requests
arrow_right Userdata arrow_right Textanalysis
import json arrow_right Contentanalysis arrow_right Imagerecognition
# GET request example
response =
requests.get('https://api.example.com/data')

# Check response status


integration_instructions Practical Example
if response.status_code == 200:
# Parse JSON response # Weather API example
data = response.json() import requests
print(data) import json
else:
print(f"Error: {response.status_code}") api_key = "your_api_key"
city = "London"
url =
f"http://api.openweathermap.org/data/2.5/weather?
q={city}&appid={api_key}"

response = requests.get(url)
if response.status_code == 200:
weather_data = response.json()
temp = weather_data['main']['temp'] - 273.15
# Convert to Celsius
description = weather_data['weather'][0]
['description']
print(f"Temperature in {city}: {temp:.1f}°C")
print(f"Conditions: {description}")

APIs provide real-time data that can enhance AI applications with


lightbulb
current information and external knowledge
Practical Web Scraping and API Projects

apps Project Ideas code Step-by-Step Example: Weather Dashboard

Real-time # Step 1: Import libraries


dashboard hub Data Aggregator import requests
Dashboard import json
arrow_right Multiplesources import matplotlib.pyplot as plt
arrow_right Livedata updates
from datetime import datetime
arrow_right Unifiedformat
arrow_right Visualmetrics
# Step 2: Fetch weather data
def get_weather_data(city, api_key):
url =
f"http://api.openweathermap.org/data/2.5/weather?
alt_route AI Data Pipeline monitoring
Price Monitor q={city}&appid={api_key}"
response = requests.get(url)
arrow_right Automatedcollection arrow_right Trackchanges return response.json()
arrow_right Preprocessingworkflow arrow_right Alertsystem
# Step 3: Process and visualize
def create_dashboard(data):
# Extract temperature
temp = data['main']['temp'] - 273.15

# Create simple visualization


plt.figure(figsize=(8, 4))
plt.bar(['Temperature'], [temp],
color='skyblue')
plt.title(f"Current Temperature in
{data['name']}")
plt.ylabel('°C')
plt.show()

Extension ideas: Add forecast data, multiple cities comparison,


lightbulb
historical trends, or integrate with AI for weather predictions
Building a Custom Recipe Generator with AI

restaurant_menu Project Overview psychology AI Integration


# Call AI model
1 2 3 4
response = openai.Completion.create(
engine="text-davinci-003",
Input Process Generate Output
prompt=prompt,
Collect Format AI Get recipe Display max_tokens=300,
ingredients prompt from AI formatted temperature=0.7
from user recipe )

# Extract and format recipe


arrow_right AI-poweredrecipe creation recipe = response.choices[0].text.strip()
return recipe
arrow_right Personalizedbased on ingredients
# User interface function
arrow_right Interactiveuser experience
def recipe_app():
print("Welcome to AI Recipe Generator!")
ingredients = input("Enter ingredients
code Core Implementation (comma separated): ")
ingredients_list = [i.strip() for i in
ingredients.split(",")]
# Import required libraries
recipe = generate_recipe(ingredients_list)
import openai
print("\\nHere's your recipe:\\n")
import os
print(recipe)
# Set API key
openai.api_key = os.getenv("OPENAI_API_KEY")
Example output:
# Define recipe generation function
Creamy Chicken Pasta
def generate_recipe(ingredients):
# Format ingredients for prompt
ingredients_str = ", ".join(ingredients) Ingredients:
- 2 chicken breasts, diced
- 300g pasta
# Create AI prompt
- 1 cup heavy cream
prompt = f"Create a recipe using:
- 2 cloves garlic, minced
{ingredients_str}"
- Salt and pepper to taste

Instructions:
1. Cook pasta according to package directions
2. Sauté chicken until golden
3. Add garlic and cook for 1 minute
4. Add cream and simmer for 5 minutes
5. Combine with pasta and serve

extension Extension Ideas


arrow_right Adddietary restrictionssupport

arrow_right Includecooking timeestimates

arrow_right Createshopping listsfor missing ingredients

arrow_right Addrating systemfor generated recipes

This project demonstrates how to integrate AI into a practical


lightbulb
Python application
Creating a Smart To-Do List with AI

checklist Project Overview psychology AI Integration


# AI task categorization and prioritization
1 2 3 4
def analyze_task_with_ai(task_description):
prompt = f"""
Input Analyze Prioritize Suggest
Categorize and prioritize the following
Collect tasks AI AI ranks by Provide smart task: "{task_description}"
from user categorizes importance recommendations Return a JSON object with 'category' and
tasks 'priority' (1-5, 5=highest)
"""
arrow_right AI-poweredtask prioritization response = openai.Completion.create(
engine="text-davinci-003",
arrow_right Smartcategorization prompt=prompt,
max_tokens=100
arrow_right Personalizedsuggestions
)

return
code Core Implementation json.loads(response.choices[0].text.strip())

# Import required libraries


import openai # Add new task with AI analysis
import json def add_task(description):
import datetime ai_result =
analyze_task_with_ai(description)
# Initialize task list task = Task(
tasks = [] description=description,
category=ai_result['category'],
# Define task class priority=ai_result['priority']
class Task: )
def __init__(self, description, tasks.append(task)
category=None, priority=None): return task
self.description = description
self.category = category # Get AI suggestions for task completion
self.priority = priority def get_ai_suggestions(task):
self.created_at = prompt = f"Provide 3 suggestions to
datetime.datetime.now() complete this task: {task.description}"
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=150
)
return response.choices[0].text.strip()

extension Extension Ideas


arrow_right Adddeadlineestimation

arrow_right Includecalendar integration

arrow_right Createproductivity analytics

arrow_right Addcollaboration features

This project demonstrates how to enhance productivity with


lightbulb
AI-powered task management
Developing a Travel Blog Analyzer with AI

travel_explore Project Overview psychology AI Integration


# Call AI model for analysis
1 2 3 4
response = openai.Completion.create(
engine="text-davinci-003",
Collect Extract Analyze Present
prompt=prompt,
Gather blog Identify key Process with Display max_tokens=300,
entries info AI insights temperature=0.3
)

arrow_right Extractrestaurant names # Parse the AI response


result_text = response.choices[0].text.strip()
arrow_right Identifypopular dishes try:
result = json.loads(result_text)
arrow_right Generatetravel summaries
return result
except json.JSONDecodeError:
return {"raw_response": result_text}
code Core Implementation
# Generate travel summary
# Import required libraries def generate_summary(blog_entry):
prompt = f"Summarize this travel blog
import openai
entry in 3 sentences: {blog_entry[:500]}"
import json
response = openai.Completion.create(
import re
engine="text-davinci-003",
prompt=prompt,
# Function to read blog entries
max_tokens=150
def read_blog_entries(file_path):
)
with open(file_path, 'r') as file:
return response.choices[0].text.strip()
content = file.read()
return content.split('---') # Split by
entries

# Function to extract key info with AI extension Extension Ideas


def extract_key_info(blog_entry):
prompt = f""" arrow_right Addmap visualizationof locations
Extract the following from this travel
blog entry: arrow_right Createrestaurant ratingssystem
1. Restaurant names
arrow_right Includeimage analysisfrom blogs
2. Popular dishes
3. Locations mentioned arrow_right Additinerary plannerbased on insights
4. Overall sentiment

Blog entry: {blog_entry} This project demonstrates how to extract insights from
lightbulb
""" unstructured text data using AI
Conclusion and Further Learning
summarize Key Takeaways school Resources for Further Learning
code Python Fundamentals account_tree Data Structures
menu_book Books video_library Online Courses
functions Functions & Modules description File Handling arrow_right Python for Data Analysis arrow_right DeepLearning.AI
arrow_right Deep Learning with Python arrow_right Coursera Python
psychology AI Integration analytics Data Visualization
arrow_right Automate the Boring Stuff Specialization
arrow_right Udacity AI Programming
language Web Scraping & APIs smart_toy Practical AI Projects

arrow_right Python is thepreferred languagefor AI development


arrow_right Practical applicationreinforces learning description Documentation groups Communities
arrow_right Python Official Docs arrow_right Stack Overflow
arrow_right AI integrationenhances capabilitiesof Python applications
arrow_right TensorFlow & PyTorch arrow_right Reddit r/learnpython
arrow_right Pandas & NumPy arrow_right GitHub Open Source

rocket_launch Next Steps


arrow_right Build projectsthat solve real problems
arrow_right Contributeto open source AI projects
"The journey of learning Python and AI is ongoing.
arrow_right Specializein an AI domain of interest
lightbulb Continue exploring, building, and innovating. The
possibilities are endless!" arrow_right Stay updatedwith latest AI developments
Practical Web Scraping and API Projects

apps Project Ideas code Building a Weather Dashboard

Real-time # Step 1: Import libraries


dashboard hub Data Aggregator import requests
Dashboard import json
arrow_right Multiplesources import matplotlib.pyplot as plt
arrow_right Livedata updates
from datetime import datetime
arrow_right Unifiedformat
arrow_right Visualmetrics
# Step 2: Define function to get weather data
def get_weather_data(city, api_key):
url =
f"http://api.openweathermap.org/data/2.5/weather?
alt_route AI Data Pipeline monitoring
Price Monitor q={city}&appid={api_key}"
response = requests.get(url)
arrow_right Automatedcollection arrow_right Trackchanges if response.status_code == 200:
return response.json()
arrow_right Preprocessingworkflow arrow_right Alertsystem
return None

# Step 3: Process and visualize data


def create_dashboard(cities, api_key):
weather_data = []
for city in cities:
data = get_weather_data(city, api_key)
if data:
temp = data['main']['temp'] - 273.15
weather_data.append({
'city': city,
'temperature': temp
})
# Create visualization
cities = [item['city'] for item in
weather_data]
temps = [item['temperature'] for item in
weather_data]
plt.bar(cities, temps)
plt.title('Current Temperature by City')
plt.ylabel('Temperature (°C)')
plt.show()

Extension ideas: Add forecast data, historical trends, or integrate


lightbulb
with AI for weather predictions
Custom Recipe Generator Project

restaurant_menu Project Overview code Core Implementation


arrow_right AI-poweredrecipe creation
# Import required libraries
arrow_right Based onavailable ingredients import openai
import json
arrow_right Considersdietary restrictions
# Function to generate recipe
arrow_right Providesstep-by-stepinstructions def generate_recipe(ingredients,
restrictions=None):
# Format ingredients
format_list_numbered Implementation Steps
ingredients_str = ", ".join(ingredients)

# Create prompt
User Interface prompt = f"Create a recipe using:
1 {ingredients_str}"
Create input form for ingredients and preferences
if restrictions:
prompt += f" that is {restrictions}"
2 Input Processing
# Call AI API
Validate and format user input response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
AI Integration max_tokens=500
3 )
Generate prompts and process responses
return response.choices[0].text.strip()

4 Output Display
Present recipes in readable format
psychology Python Concepts Applied
arrow_right Functions- modular code structure

arrow_right String manipulation- formatting prompts

arrow_right API integration- connecting to AI services

arrow_right Error handling- robust application

This project demonstrates how to integrate AI into practical


lightbulb
applications using Python
Smart To-Do List Project
checklist Project Overview code Core Implementation
arrow_right AI-poweredtask prioritization
# Task class definition
arrow_right Smartscheduling class Task:
def __init__(self, title, description="",
arrow_right Dynamicorganization priority="medium"):
self.title = title
arrow_right Automatedreminders self.description = description
self.priority = priority
self.completed = False
format_list_numbered Implementation Steps # Smart To-Do List class
class SmartTodoList:
Data Structure def __init__(self):
1 self.tasks = []
Create task class with attributes and methods
def add_task(self, task):
self.tasks.append(task)
Task Management self.prioritize_tasks() # Auto-
2 prioritize
Implement add, edit, delete functionality

3 AI Prioritization psychology AI Integration for Prioritization


Integrate AI for intelligent task ordering
# AI-powered task prioritization
def prioritize_tasks(self):
if not self.tasks:
4 User Interface return
Build interactive command-line or GUI
# Create task descriptions for AI
task_descriptions = []
for task in self.tasks:
desc = f"{task.title}:
{task.description}"
task_descriptions.append(desc)

# Use AI to prioritize (simplified


example)
prompt = "Prioritize these tasks by
importance: "\n"
prompt += "\n".join(task_descriptions)

# In a real implementation, this would


call an AI API
# For now, we'll sort by title length as a
placeholder
self.tasks.sort(key=lambda x:
len(x.title), reverse=True)

This project demonstrates data structures, functions, and AI


lightbulb
integration in a practical application
Travel Blog Analyzer Project

travel_explore Project Overview code Core Implementation


arrow_right Extractkey information from blogs
# Blog analyzer class
arrow_right Identifyrestaurants and attractions class TravelBlogAnalyzer:
def __init__(self):
arrow_right Analyzesentiment and popularity self.blogs = []
self.locations = {}
arrow_right Visualizetravel patterns self.restaurants = []

def load_blog(self, filepath):


format_list_numbered Implementation Steps
with open(filepath, 'r') as file:
content = file.read()
self.blogs.append(content)
Blog Processing return content
1
Read and parse blog files

psychology AI Integration for Analysis


2 Text Analysis
Extract locations and entities # Extract key information using AI
def extract_key_info(self, blog_content):
# Create prompt for AI analysis
prompt = f"""
3 AI Integration Extract the following from this travel
Identify restaurants and attractions blog:
1. Restaurant names and dishes mentioned
2. Tourist attractions visited
3. Overall sentiment
4 Data Visualization (positive/negative/neutral)
Create maps and charts Blog content: {blog_content[:1000]}
"""

# In a real implementation, this would


call an AI API
# For now, we'll use a simplified approach
restaurants =
self._find_restaurants(blog_content)
attractions =
self._find_attractions(blog_content)
sentiment =
self._analyze_sentiment(blog_content)

return restaurants, attractions, sentiment

This project combines file handling, text analysis, and AI


lightbulb
integration to extract insights from unstructured data
Dream Vacation Planner Project

flight Project Overview code Core Implementation


arrow_right Multi-citytrip planning
# Vacation planner class
arrow_right Personalizeditineraries import csv
import json
arrow_right AI-poweredrecommendations
class VacationPlanner:
arrow_right Data-drivensuggestions def __init__(self):
self.destinations = {}
self.activities = []
format_list_numbered Implementation Steps def load_travel_data(self, csv_file):
with open(csv_file, 'r') as file:
Data Processing reader = csv.DictReader(file)
1 for row in reader:
Load and process travel data from CSV files city = row['city']
if city not in
self.destinations:
Data Structures self.destinations[city] = []
2 self.destinations[city].append({
Organize destinations and activities 'activity': row['activity'],
'category': row['category']
})
3 AI Integration
Generate personalized itineraries
psychology AI Integration for Itineraries
4 User Interface # Generate personalized itinerary using AI
Interactive vacation planner def generate_itinerary(self, cities,
preferences):
itinerary = {}

for city in cities:


if city in self.destinations:
# Create AI prompt for this city
activities = self.destinations[city]
prompt = f"""
Create a day itinerary for {city}
with these activities:
{json.dumps(activities[:5])}
User preferences: {preferences}
"""

# In a real implementation, this


would call an AI API
# For now, we'll return a simple
structure
itinerary[city] = activities[:3] #
First 3 activities

return itinerary

This project combines file handling, data structures, and AI


lightbulb
integration to create a practical travel planning application
Conclusion and Next Steps

summarize Key Concepts Learned menu_book Resources for Further Learning


Python Basics Data Structures Functions File Handling
auto_stories Books school Online Courses
Control Flow AI Integration Data Analysis Visualization
arrow_right Python Crash Course arrow_right DeepLearning.AI
Web Scraping APIs
arrow_right Deep Learning with arrow_right Coursera ML Courses
Python
trending_up Next Steps
arrow_right Exploreadvanced AI topics
arrow_right Contribute toopen-source projects groups Communities code Projects
arrow_right Buildpersonal AI applications arrow_right Stack Overflow arrow_right Kaggle Competitions
arrow_right JoinAI communities arrow_right GitHub arrow_right Personal Portfolios

Your Python & AI Journey Has Just Begun! psychology Python + AI Integration
Keep exploring, building, and innovating with the skills you've arrow_right Leverage AI librariesfor complex tasks
learned
arrow_right Build AI-poweredapplications
arrow_right Automate workflowswith Python scripts
arrow_right Create data pipelinesfor AI projects

You might also like