AI Lab Practical Code Examples in Python
AI Lab Practical Code Examples in Python
Natasha Singh
This document has the code snippets for all the Lab Manual Questions for
Intro to AI Lab using Python.
1
2025 Introduction to AI using Python
def chatbot_response(user_input):
responses = {
"hello": "Hi there!",
"how are you": "I’m just a bot, but I’m doing fine!",
"bye": "Goodbye!",
"name": "I’m a simple chatbot created with Python."
}
return [Link](user_input.lower(), "Sorry, I don’t understand that.")
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
print("Bot:", chatbot_response(user_input))
2. Implement a simple Tic-Tac-Toe game where two players can play against
each other.
def print_board(board):
for row in board:
print("|".join(row))
print("-" * 5)
def play_game():
board = [[" "]*3 for _ in range(3)]
player = "X"
for turn in range(9):
print_board(board)
row = int(input(f"Player {player}, enter row (0-2): "))
2
2025 Introduction to AI using Python
play_game()
import random
def print_grid(grid):
for row in grid:
print(" ".join(row))
def vacuum_cleaner(grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "D":
print(f"Cleaning dirt at ({i},{j})")
grid[i][j] = "C"
vacuum_cleaner(grid)
print("Final Grid:")
print_grid(grid)
4. Simulate a basic traffic light system using an AI agent that changes lights
based on time.
import time
3
2025 Introduction to AI using Python
for _ in range(cycles):
for light, duration in zip(lights, times):
print(f"Traffic Light: {light}")
[Link](duration)
while queue:
curr = [Link]()
if curr == goal:
break
for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
x, y = curr[0] + dx, curr[1] + dy
if 0 <= x < rows and 0 <= y < cols and maze[x][y] != 1 and (x,y) not in visited:
[Link]((x, y))
[Link]((x, y))
parent[(x, y)] = curr
# Reconstruct path
path = []
step = goal
while step:
[Link](step)
step = [Link](step)
[Link]()
return path
maze = [
[0, 1, 0, 0],
[0, 1, 0, 1],
[0, 0, 0, 0],
[1, 1, 1, 0]
]
start = (0, 0)
4
2025 Introduction to AI using Python
goal = (3, 3)
print("DFS Traversal:")
dfs(graph, ’A’)
import heapq
while heap:
cost, node = [Link](heap)
if node in visited:
continue
[Link](node)
5
2025 Introduction to AI using Python
graph = {
’A’: {’B’: 2, ’C’: 4},
’B’: {’C’: 1, ’D’: 7},
’C’: {’E’: 3},
’D’: {’F’: 1},
’E’: {’D’: 2, ’F’: 5},
’F’: {}
}
start = ’A’
print("Shortest distances from A:", dijkstra(graph, start))
import heapq
def heuristic(state):
dist = 0
for i in range(3):
for j in range(3):
val = state[i][j]
if val != 0:
goal_x, goal_y = (val - 1) // 3, (val - 1) % 3
dist += abs(i - goal_x) + abs(j - goal_y)
return dist
def get_neighbors(state):
moves = []
x, y = [(ix, iy) for ix, row in enumerate(state) for iy, i in enumerate(row) if i =
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < 3 and 0 <= ny < 3:
new_state = [row[:] for row in state]
new_state[x][y], new_state[nx][ny] = new_state[nx][ny], new_state[x][y]
[Link](new_state)
return moves
def a_star(start):
heap = [(heuristic(start), start)]
6
2025 Introduction to AI using Python
visited = set()
while heap:
h, state = [Link](heap)
if state == goal_state:
print("Goal reached!")
return
[Link](str(state))
for neighbor in get_neighbors(state):
if str(neighbor) not in visited:
[Link](heap, (heuristic(neighbor), neighbor))
print("No solution found.")
import random
def objective(x):
return -(x**2) + 10 # Parabola with maximum at x=0
def hill_climb():
current = [Link](-10, 10)
step_size = 0.1
for _ in range(1000):
neighbor = current + [Link](-step_size, step_size)
if objective(neighbor) > objective(current):
current = neighbor
print("Best solution:", round(current, 2), "Value:", round(objective(current), 2))
hill_climb()
def objective(x):
return -(x**2) + 10 # Peak at x=0
def simulated_annealing():
current = [Link](-10, 10)
temp = 100.0
cooling = 0.99
while temp > 0.01:
next_guess = current + [Link](-1, 1)
7
2025 Introduction to AI using Python
simulated_annealing()
def solve(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
for num in range(1, 10):
if is_valid(board, i, j, num):
board[i][j] = num
if solve(board):
return True
board[i][j] = 0
return False
return True
sudoku = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
if solve(sudoku):
8
2025 Introduction to AI using Python
graph = {
0: [1, 2],
1: [0, 2, 3],
2: [0, 1],
3: [1]
}
colors = ["Red", "Green", "Blue"]
13. Create an AI that plays Rock, Paper, Scissors with random choices.
import random
def play_rps():
choices = ["rock", "paper", "scissors"]
ai_choice = [Link](choices)
user = input("Choose rock, paper or scissors: ").lower()
9
2025 Introduction to AI using Python
if user == ai_choice:
print("It’s a tie!")
elif (user == "rock" and ai_choice == "scissors") or \
(user == "paper" and ai_choice == "rock") or \
(user == "scissors" and ai_choice == "paper"):
print("You win!")
else:
print("AI wins!")
play_rps()
14. Implement the Minimax Algorithm for a simple game like Tic-Tac-Toe.
def print_board(board):
for row in board:
print("|".join(row))
print()
def is_full(board):
return all(cell != " " for row in board for cell in row)
10
2025 Introduction to AI using Python
return best
def best_move(board):
best_score = -float(’inf’)
move = None
for i in range(3):
for j in range(3):
if board[i][j] == " ":
board[i][j] = "O"
score = minimax(board, False)
board[i][j] = " "
if score > best_score:
best_score = score
move = (i, j)
return move
# Initialize game
board = [[" "]*3 for _ in range(3)]
for _ in range(9):
print_board(board)
x, y = map(int, input("Enter row and column (0-2): ").split())
if board[x][y] != " ":
print("Invalid move")
continue
board[x][y] = "X"
if check_winner(board, "X"):
print("You win!")
break
if is_full(board):
print("Draw")
break
ai_x, ai_y = best_move(board)
board[ai_x][ai_y] = "O"
if check_winner(board, "O"):
print_board(board)
print("AI wins!")
break
11
2025 Introduction to AI using Python
15. Create a rule-based expert system to recommend movies based on user input.
def recommend_movie():
print("Answer yes or no:")
likes_action = input("Do you like action movies? ").lower() == "yes"
likes_romance = input("Do you enjoy romantic movies? ").lower() == "yes"
likes_comedy = input("Do you like comedy? ").lower() == "yes"
recommend_movie()
16. Represent a family tree using Python dictionaries and query relationships.
family = {
"John": {"father": "Robert", "mother": "Linda"},
"Alice": {"father": "John", "mother": "Eva"},
"Bob": {"father": "John", "mother": "Eva"},
"Eva": {"father": "Michael", "mother": "Sarah"}
}
def get_parents(name):
if name in family:
return family[name]["father"], family[name]["mother"]
return None, None
def get_grandparents(name):
father, mother = get_parents(name)
return get_parents(father) + get_parents(mother)
12
2025 Introduction to AI using Python
17. Write a Python program to count the number of words in a given sentence.
def count_words(sentence):
words = [Link]()
return len(words)
def detect_sentiment(sentence):
sentence = [Link]()
pos = [word for word in positive_words if word in sentence]
neg = [word for word in negative_words if word in sentence]
def is_spam(email_text):
spam_keywords = ["buy now", "free", "click here", "winner", "subscribe"]
text = email_text.lower()
for keyword in spam_keywords:
if keyword in text:
return True
return False
13
2025 Introduction to AI using Python
20. Write a Python program to predict the next number in a simple sequence
(e.g., 2, 4, 6, ?).
def predict_next(seq):
if len(seq) < 2:
return "Not enough data"
diff = seq[1] - seq[0]
if all(seq[i+1] - seq[i] == diff for i in range(len(seq)-1)):
return seq[-1] + diff
return "Pattern not recognized"
def keyword_chatbot(user_input):
user_input = user_input.lower()
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I assist you?"
elif "weather" in user_input:
return "It might be sunny or rainy. Check your weather app!"
elif "name" in user_input:
return "I am a keyword-based chatbot."
elif "bye" in user_input:
return "Goodbye!"
else:
return "I’m not sure how to respond to that."
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
print("Bot:", keyword_chatbot(user_input))
22. Write a program to classify even and odd numbers using a simple rule-based
AI.
def classify_number(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
14
2025 Introduction to AI using Python
def is_palindrome(text):
cleaned = ’’.join(filter([Link], text)).lower()
return cleaned == cleaned[::-1]
25. Develop a movie recommendation system using a list of genres and user input.
movies = {
"Action": ["Mad Max", "John Wick"],
"Comedy": ["The Hangover", "Superbad"],
"Romance": ["The Notebook", "Titanic"],
"Horror": ["The Conjuring", "Get Out"]
}
def recommend_movie(genre):
genre = [Link]()
return [Link](genre, ["No recommendations available"])
15
2025 Introduction to AI using Python
import random
def number_guessing_game():
number = [Link](1, 100)
attempts = 0
while True:
guess = int(input("Guess the number (1{100): "))
attempts += 1
if guess == number:
print(f"Correct! You guessed it in {attempts} attempts.")
break
elif guess < number:
print("Hint: Try a higher number.")
else:
print("Hint: Try a lower number.")
number_guessing_game()
27. Simulate an AI system that suggests the best route to take based on traffic
conditions.
def suggest_route(traffic):
if traffic == "high":
return "Take the bypass road."
elif traffic == "moderate":
return "Take the main road."
elif traffic == "low":
return "Fastest route is via city center."
else:
return "Invalid traffic input."
def detect_spam_words(text):
spam_words = ["free", "win", "cash", "buy", "offer", "click"]
found = [word for word in spam_words if word in [Link]()]
return found if found else ["No spam words detected."]
16
2025 Introduction to AI using Python
import difflib
30. Implement a self-learning agent that improves its guesses over time.
import random
class SelfLearningGuesser:
def __init__(self):
self.guess_range = [1, 100]
def guess(self):
return (self.guess_range[0] + self.guess_range[1]) // 2
agent = SelfLearningGuesser()
hidden_number = [Link](1, 100)
[Link](hidden_number)
17
2025 Introduction to AI using Python
18
2025 Introduction to AI using Python
19
2025 Introduction to AI using Python
20
2025 Introduction to AI using Python
21
2025 Introduction to AI using Python
logic, graphs).
46. Q: What is an expert system?
A: A rule-based AI system that mimics human decision-making in specific domains.
47. Q: How is a rule-based system implemented in Python?
A: Using if-else or case-matching statements based on user input.
48. Q: What is a family tree in AI?
A: A representation of relationships using graphs or dictionaries.
49. Q: How are relationships queried in a family tree?
A: By traversing links in dictionaries or graphs.
50. Q: What is NLP in AI?
A: Natural Language Processing enables machines to understand, interpret, and
generate human language.
51. Q: What is tokenization?
A: The process of splitting a sentence into words (tokens).
52. Q: How do you count words in a sentence in Python?
A: Using split() method: len([Link]()).
53. Q: What is sentiment analysis?
A: The process of determining whether a sentence expresses positive, negative, or
neutral emotion.
54. Q: What is a positive/negative word detector?
A: A system that matches words against lists of positive and negative words to
detect sentiment.
55. Q: How does a spam email classifier work?
A: It checks for specific spam keywords like “buy now”, “free”, “click here” in the
message.
56. Q: What is a rule-based AI?
A: An AI that makes decisions using fixed rules (if-else logic).
57. Q: How can AI predict the next number in a sequence?
A: By identifying patterns like arithmetic or geometric progressions.
58. Q: How does an AI detect palindromes?
A: By checking if the string is the same forwards and backwards.
59. Q: What is a self-learning agent?
A: An agent that improves its behavior based on past experience or feedback.
60. Q: How can AI suggest routes based on traffic?
A: Using if-else conditions or real-time traffic data to recommend the best path.
61. Q: What is autocorrection in text?
A: AI compares input word with a dictionary and suggests the closest match using
string similarity.
22
2025 Introduction to AI using Python
Extra Questions
62. Q: How does BFS ensure the shortest path?
A: It visits all nodes at distance d before d+1, so the first time it reaches the goal
is via the shortest path.
63. Q: When is DFS preferred over BFS?
A: DFS is preferred when memory is limited or when searching for any solution is
sufficient (not necessarily shortest).
64. Q: How does the heuristic in A search ensure if it’s admissible?
A: It never overestimates the true cost to the goal, guaranteeing an optimal path.
65. Q: Define “heuristic” in the context of A search.
A: A function that estimates the cost from the current state to the goal, guiding
the search.
66. Q: Why use Manhattan distance for the 8-puzzle?
A: It visits all nodes at distance d before d+1, so the first time it reaches the goal
is via the shortest path.
67. Q: What makes A more efficient than Dijkstra on large graphs?
A: Its heuristic narrows focus to promising paths, reducing the explored nodes.
68. Q: How does Simulated Annealing avoid local optima?
A: By occasionally accepting worse moves with a probability that decreases over
time (”temperature”), allowing escape.
69. Q: What is the “temperature” parameter in Simulated Annealing?
A: A value that controls how likely the algorithm accepts worse solutions; it cools
down as iterations progress.
70. Q: Compare Hill Climbing and Simulated Annealing.
A: Hill Climbing is greedy and faster but risks local optima; Simulated Annealing
is slower but more robust against local traps.
71. Q: How do you choose parameters for Simulated Annealing?
A: Initial temperature, cooling schedule, and termination conditions are chosen
based on experimentation or domain knowledge.
72. Q: What is a fitness function in optimization problems?
A: It evaluates how good a candidate solution is, guiding search algorithms toward
optimal outcomes.
23