Python Programming Lab Report
Python Programming Lab Report
Comments
Implementation Methods
The implementation involves creating a series of Python scripts, each focusing on a specific concept
of Python programming. The structure is as follows:
• Basic Syntax and Operations: Scripts were designed to introduce printing statements,
variable declarations, and basic arithmetic operations.
• Conditional Logic: Scripts cover if-else statements, logical operators, and comparison
operators to introduce decision-making in programs.
Loops: Implementation of while loops, for loops, and nested loops to handle repetitive tasks
•
efficiently.
Data Structures: Scripts were written to demonstrate lists, 2D lists, tuples, and dictionaries,
• along with their operations and use cases.
Functions: Covered function creation, parameters, return values, and practical use cases like
• converting text to emoji.
25
age
72.5
Sharif Md Mehedi Hasan
True
name = input('What is your name?')
address = input('Where are you from?')
print(name + ' lives in '+ address)
What is your name?Sowrov
Where are you from?Dhaka
Sowrov lives in Dhaka
celsius = input('Temperature in Celsius ')
celsius = int(celsius)
fahrenheit = (celsius * (9/5)) + 32
print(fahrenheit)
Temperature in Celsius 40
104.0
course_name = 'Learn Python Programming'
print(course_name[1:-1])
earn Python Programmin
name = 'Nuruzzaman Faruqui' code_name = 'NF'
message = name + '(' + code_name + ') teaches AI'
print(message) message_1 = f'{name}({code_name})
teaches AI' print(message_1)
Nuruzzaman Faruqui(NF) teaches AI
Nuruzzaman Faruqui(NF) teaches AI
course_name = 'Learn Python Programming'
print(len(course_name))
print(course_name.upper())
print(course_name.lower())
print(course_name)
print(course_name.find('Python'))
print(course_name.replace('Learn', 'Master'))
print('learn' in course_name)
24
LEARN PYTHON PROGRAMMING
learn python programming
Learn Python Programming
6
Master Python Programming
False
print(5-3)
print(5+3)
print(5*3)
print(5/3)
print(5//3)
print(5%3)
print(5**3)
x = 5
x = x + 5
x += 5
print(x)
y = 5
y -= 2
print(y)
z = 5 + 3 * 2 ** 2
print(z)
p = (5+3) * 2 ** 2
print(p)
q = (1+2) * (5-3)
print(q)
2
8
15 1.6666666666666667 1 2 125 15 3 17 32 6
import math
print(math.ceil(5.7))
print(math.floor(5.7))
print(math.factorial(5))
x = 5.7
print(round(x))
print(abs(-5.7))
6
5
120
6
5.7
Conditional statements and logical/comparison operators.
is_rainy = False is_sunny = True
if is_rainy:
print('Carry an umbrella')
elif is_sunny:
print('No need to carry the umbrella')
else:
print('Please check the weather')
good_condition = True
reasonable_price = False
poor_foundation = False
We are interested
It is a good deal
price = 9
if price == 10:
print("We will buy it")
if price != 10:
print("The price is not 10")
if price > 10:
print("It is expensive")
if price <= 10:
print("It is cheap")
for x in range(10):
print(x)
for y in range(4):
print(f"({x}, {y})")
(0, 0) (0, 1) (0, 2) (0, 3) (1, 0) (1, 1) (1, 2) (1, 3) (2, 0) (2,
1) (2, 2) (2, 3) (3, 0) (3, 1) (3, 2) (3, 3)
Lists
grocery_list = ['egg', 'rice', 'bread', 'sugar']
grocery_list[1] = 'oil' print(grocery_list[1:2])
print(grocery_list)
price = [5, 10, 15, 1, 3, 7]
max = price[0]
for value in price:
welcome("Nuruzzaman", "Faruqui")
Total cost: $14
Hi Nuruzzaman Faruqui
def add(number_1, number_2):
return number_1 + number_2
print(add(1, 2))
def emoji_converted(message):
separate_words = message.split(' ')
emoji = {
😊
":)": " ",
☹
":(": " "
}
output = ""
for word in separate_words:
output += emoji.get(word, word) + " "
return output
• Data Manipulation: Using lists, tuples, and dictionaries for managing data.
Conclusion
The lessons provide a comprehensive foundation for Python programming, covering
essential topics required for general-purpose programming. They offer practical
examples to solidify concepts and prepare learners for real-world Python applications.
#2 Experiment Title : Solving a Maze Using Depth-First Search (DFS) and
Breadth-First Search (BFS)
Purpose of the Experiment
To implement a pathfinding algorithm capable of navigating through a maze to find the
shortest path from a starting point ("A") to a goal point ("B") while visualizing the solution
and explored states.
Implementation Methods
• Node Class: Represents a node in the search tree with its state, parent, and action.
• StackFrontier: Implements a stack-based frontier for DFS.
•
QueueFrontier: Extends StackFrontier for BFS by overriding the remove method to
dequeue from the front.
•
Maze Class: Handles maze creation, validation, wall tracking, and pathfinding.
➢ Maze Input: Read from a text file where walls, start, and goal points are defined.
➢ neighbors(): Determines valid neighboring cells for exploration.
➢ solve(): Explores the maze using the chosen algorithm and finds the solution path.
➢ output_image(): Generates a visual representation of the maze, showing walls, the
solution path, and explored cells.
Code :
Maze Solver
import sys
class Node():
def __init__(self, state, parent, action):
self.state = state
self.parent = parent
self.action = action
class StackFrontier():
def __init__(self):
self.frontier = []
def empty(self):
return len(self.frontier) == 0
def remove(self):
if self.empty():
raise Exception("empty frontier")
else:
node = self.frontier[-1]
self.frontier = self.frontier[:-1]
return node
class QueueFrontier(StackFrontier):
def remove(self):
if self.empty():
raise Exception("empty frontier")
else:
node = self.frontier[0]
self.frontier = self.frontier[1:]
return node
class Maze():
self.solution = None
def print(self):
solution
print() = self.solution[1] if self.solution is not None else
None for i, row in enumerate(self.walls):
def solve(self):
"""Finds a solution to maze, if one exists."""
# Keep track of number of states explored
self.num_explored = 0
# Initialize frontier to just the starting position
start = Node(state=self.start, parent=None, action=None)
frontier = QueueFrontier()
frontier.add(start)
# Initialize an empty explored set
self.explored = set()
# Keep looping until solution found
while True:
# Walls
if col:
fill = (40, 40, 40)
# Start
elif (i, j) == self.start:
fill = (255, 0, 0)
# Goal
elif (i, j) == self.goal:
fill = (0, 171, 28)
# Solution
elif solution is not None and show_solution and (i, j)
in solution:
fill = (220, 235, 113)
# Explored
elif solution is not None and show_explored and (i, j)
in self.explored:
fill = (212, 97, 85)
# Empty cell
else:
fill = (237, 240, 252)
# Draw cell
draw.rectangle(
([(j * cell_size + cell_border, i * cell_size +
cell_border),
((j + 1) * cell_size - cell_border, (i + 1) *
cell_size - cell_border)]),
fill=fill
)
img.save(filename)
#if len(sys.argv) != 2:
#sys.exit("Usage: python maze.py maze.txt")
m = Maze('/content/maze1.txt')
print("Maze:")
m.print()
print("Solving...")
m.solve()
print("States Explored:", m.num_explored)
print("Solution:")
m.print()
m.output_image("maze.png", show_explored=True)
5. Output
Field of Application
Conclusion
The experiment successfully implemented a maze-solving algorithm using depth-first search.
The program can read a maze from a text file, validate its format, and find a solution path
while visualizing the process. This project highlights the efficacy of stack and queue-based
data structures in solving real-world problems like pathfinding.
#3 Experiment Title Logical Sentence Evaluation and Model Checking
Purpose of the Experiment
To implement a framework for logical reasoning using propositional logic. The experiment
evaluates logical sentences under various models and determines entailments.
Implementation Methods
• Base Class (Sentence): Implements methods to define and validate logical sentences.
• Derived Classes: Implement specific logical operators, including:
o Symbol: Represents atomic propositions.
o Not: Logical negation.
o And: Conjunction.
o
Or: Disjunction.
Code:
logic.py
import itertools
class Sentence():
def formula(self):
"""Returns string formula representing logical sentence."""
return ""
def symbols(self):
"""Returns a set of all symbols in the logical sentence."""
return set()
@classmethod
def validate(cls, sentence):
if not isinstance(sentence, Sentence):
raise TypeError("must be a logical sentence")
@classmethod
def parenthesize(cls, s):
"""Parenthesizes an expression if not already
parenthesized."""
def balanced(s):
"""Checks if a string has balanced parentheses."""
count = 0
for c in s:
if c == "(":
count += 1
elif c == ")":
if count <= 0:
return False
count -= 1
return count == 0
if not len(s) or s.isalpha() or (
s[0] == "(" and s[-1] == ")" and balanced(s[1:-1])
):
return s
else:
return f"({s})"
class Symbol(Sentence):
def __hash__(self):
return hash(("symbol", self.name))
def __repr__(self):
return self.name
def formula(self):
return self.name
def symbols(self):
return {self.name}
class Not(Sentence):
def __init__(self, operand):
Sentence.validate(operand)
self.operand = operand
def __hash__(self):
return hash(("not", hash(self.operand)))
def __repr__(self):
return f"Not({self.operand})"
def formula(self):
return "¬" + Sentence.parenthesize(self.operand.formula())
def symbols(self):
return self.operand.symbols()
class And(Sentence):
def __init__(self, *conjuncts):
for conjunct in conjuncts:
Sentence.validate(conjunct)
self.conjuncts = list(conjuncts)
def __hash__(self):
return hash(
("and", tuple(hash(conjunct) for conjunct in
self.conjuncts))
)
def __repr__(self):
conjunctions = ", ".join(
[str(conjunct) for conjunct in self.conjuncts]
)
return f"And({conjunctions})"
def symbols(self):
return set.union(*[conjunct.symbols() for conjunct in
self.conjuncts])
class Or(Sentence):
def __init__(self, *disjuncts):
for disjunct in disjuncts:
Sentence.validate(disjunct)
self.disjuncts = list(disjuncts)
def __repr__(self):
disjuncts = ", ".join([str(disjunct) for disjunct in
self.disjuncts])
return f"Or({disjuncts})"
def formula(self):
if len(self.disjuncts) == 1:
return self.disjuncts[0].formula()
return " ∨ ".join([Sentence.parenthesize(disjunct.formula())
for disjunct in self.disjuncts])
def symbols(self):
return set.union(*[disjunct.symbols() for disjunct in
self.disjuncts])
class Implication(Sentence):
def __init__(self, antecedent, consequent):
Sentence.validate(antecedent)
Sentence.validate(consequent)
self.antecedent = antecedent
self.consequent = consequent
def __hash__(self):
return hash(("implies", hash(self.antecedent),
hash(self.consequent)))
def __repr__(self):
return f"Implication({self.antecedent}, {self.consequent})"
def formula(self):
antecedent = Sentence.parenthesize(self.antecedent.formula())
consequent = Sentence.parenthesize(self.consequent.formula())
return f"{antecedent} => {consequent}"
def symbols(self):
return set.union(self.antecedent.symbols(),
self.consequent.symbols())
class Biconditional(Sentence):
def __init__(self, left, right):
Sentence.validate(left)
Sentence.validate(right)
self.left = left
self.right = right
def __hash__(self):
return hash(("biconditional", hash(self.left),
hash(self.right)))
def __repr__(self):
return f"Biconditional({self.left}, {self.right})"
def formula(self):
left = Sentence.parenthesize(str(self.left))
right = Sentence.parenthesize(str(self.right))
return f"{left} <=> {right}"
def symbols(self):
return set.union(self.left.symbols(), self.right.symbols())
Harry.py
from logic import *
rain = Symbol("rain")
hagrid = Symbol("hagrid")
dumbledore = Symbol("dumbledore")
knowledge = And(
Implication(Not(rain), hagrid),
Or(hagrid, dumbledore),
Not(And(hagrid, dumbledore)),
dumbledore
)
print(model_check(knowledge, rain))
Output
The output determines whether the query is entailed by the knowledge base. For the given
example, the script outputs whether the proposition rain is entailed.
Field of Application
The model has practical applications in:
• Artificial intelligence for knowledge representation.
• Automated theorem proving.
•
Building intelligent agents in decision-making systems.
Conclusion
This experiment demonstrates how propositional logic can be effectively implemented and
evaluated in Python. The modular structure enables scaling for more complex logic
problems.
#4 Experiment Title: Bayesian Network Analysis using Python
Purpose of the Experiment:
The objective of this experiment is to construct and analyse a Bayesian network to model
probabilistic relationships between variables such as weather, maintenance, train schedules,
and appointments. The experiment also involves computing predictions, likelihoods, and
performing sampling techniques.
Implementation Methods
• Defined a Bayesian network using the pomegranate library.
• Utilized conditional probability tables to model dependencies between nodes.
• Performed inference to predict outcomes based on given conditions.
• Conducted sampling techniques, including rejection sampling, to analyze conditional
distributions.
Code
# model.py from
pomegranate import *
"none": 0.7,
"light": 0.2,
"heavy": 0.1
}), name="rain")
], [train.distribution]), name="appointment")
# Finalize model
model.bake()
# inference.py
from model import model
# Calculate predictions
predictions = model.predict_proba({
"train": "delayed"
})
else:
print(f"{node.name}")
for value, probability in prediction.parameters[0].items():
print(f" {value}: {probability:.4f}")
Output
Inference Output: Predictions for each variable given that the train is delayed.
Conclusion
The experiment demonstrates how Bayesian networks can effectively model and analyze
complex probabilistic relationships. By leveraging libraries like pomegranate, we can
implement inference, calculate likelihoods, and perform sampling to gain insights into
conditional probabilities and dependencies.