0% found this document useful (0 votes)
2 views25 pages

Python Lab

The document contains various Python programming tasks and their implementations, including creating and manipulating arrays with NumPy, drawing shapes using the turtle module, converting images to grayscale, visualizing game ratings with bar charts, and implementing graph algorithms like BFS and DFS. Additionally, it covers optimization techniques using hill climbing, the A* algorithm for pathfinding, and creating a simple rule-based system. Each section provides code snippets and expected outputs for clarity.

Uploaded by

web3ngineer
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)
2 views25 pages

Python Lab

The document contains various Python programming tasks and their implementations, including creating and manipulating arrays with NumPy, drawing shapes using the turtle module, converting images to grayscale, visualizing game ratings with bar charts, and implementing graph algorithms like BFS and DFS. Additionally, it covers optimization techniques using hill climbing, the A* algorithm for pathfinding, and creating a simple rule-based system. Each section provides code snippets and expected outputs for clarity.

Uploaded by

web3ngineer
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

1. Write a python program to create 1D, 2D, and 3D array using NumPy.

Perform
the following operation: Slicing, accessing element, array shapes.
import numpy as np

# Create a 1D array
array_1d = [Link]([1, 2, 3, 4, 5])
print("1D Array:", array_1d)
print("Shape of 1D Array:", array_1d.shape)

# Slicing the 1D array


print("Sliced 1D Array (elements from index 1 to 4):", array_1d[1:4])

# Create a 2D array
array_2d = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:\n", array_2d)
print("Shape of 2D Array:", array_2d.shape)

# Accessing an element in the 2D array


print("Element at (0, 2) in 2D Array:", array_2d[0, 2])

# Slicing the 2D array


print("Sliced 2D Array (first row):", array_2d[0])

# Create a 3D array
array_3d = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:\n", array_3d)
print("Shape of 3D Array:", array_3d.shape)

# Accessing an element in the 3D array


print("Element at (0, 1, 0) in 3D Array:", array_3d[0, 1, 0])

# Slicing the 3D array


print("Sliced 3D Array (first matrix):\n", array_3d[0])

1
OUTPUT:

2
2. Use turtle to draw basic shapes such as a rectangle, circle, square, star, cone
and triangle.
import turtle

def draw_square(t):
for _ in range(4):
[Link](100)
[Link](90)

def draw_rectangle(t):
for _ in range(2):
[Link](150)
[Link](90)
[Link](100)
[Link](90)

def draw_circle(t):
[Link](50)

def draw_star(t):
for _ in range(5):
[Link](100)
[Link](144)

def draw_triangle(t):
for _ in range(3):
[Link](100)
[Link](120)

def draw_shapes():
screen = [Link]()
my_turtle = [Link]()

draw_square(my_turtle)
my_turtle.penup()
my_turtle.goto(-250, 0)
my_turtle.pendown()

draw_rectangle(my_turtle)
my_turtle.penup()
my_turtle.goto(-150, -150)
my_turtle.pendown()

draw_circle(my_turtle)
my_turtle.penup()
my_turtle.goto(150, -150)
3
my_turtle.pendown()

draw_star(my_turtle)
my_turtle.penup()
my_turtle.goto(150, 0)
my_turtle.pendown()

draw_triangle(my_turtle)

[Link]()

draw_shapes()

OUTPUT:

4
3. Draw a snowman, Olympic symbol, Indian flag, and Rainbow using turtle
module in Python.
import turtle

def draw_snowman():
[Link]()
[Link](0, -150)
[Link]()
[Link](80)
[Link]()
[Link](0, 10)
[Link]()
[Link](50)
[Link]()
[Link](-15, 70)
[Link]()
[Link](5)
[Link]()
[Link](15, 70)
[Link]()
[Link](5)

def draw_olympic_symbol():
colors = ["blue", "black", "red", "yellow", "green"]
positions = [(-120, 0), (0, 0), (120, 0), (-60, -50), (60, -50)]
[Link](2)
for color, position in zip(colors, positions):
[Link]()
[Link](position)
[Link]()
[Link](color)
[Link](50)

def draw_indian_flag():
# Draw saffron rectangle
[Link]()
[Link](-180, 100)
[Link]()
[Link]("orange")
turtle.begin_fill()
for _ in range(2):
[Link](360)
[Link](90)
[Link](50)
[Link](90)
turtle.end_fill()
5
# Draw green rectangle
[Link]()
[Link](-180, 0)
[Link]()
[Link]("green")
turtle.begin_fill()
for _ in range(2):
[Link](360)
[Link](90)
[Link](50)
[Link](90)
turtle.end_fill()

# Draw Ashoka Chakra


[Link]()
[Link](0, 0)
[Link]()
[Link]("blue")
[Link](25)
for _ in range(24):
[Link]()
[Link](0, 25)
[Link]()
[Link](25)
[Link](25)
[Link](15)

def draw_rainbow():
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
radius = 200
for color in colors:
[Link]()
[Link](radius, 0)
[Link](90)
[Link]()
[Link](color)
[Link](10)
[Link](radius, 180)
radius -= 10

# drawing logic
[Link](3)

# Draw snowman
draw_snowman()
[Link]()

6
draw_olympic_symbol()
[Link]()

draw_indian_flag()
[Link]()

draw_rainbow()

# End session
[Link]()

OUTPUT:

7
4. Write a python program to converting an Image to Gray scale.
from PIL import Image, UnidentifiedImageError

def convert_to_grayscale(image_path, save_path):


try:
# Open the image and convert to grayscale
image = [Link](image_path).convert('L')
[Link]() # Display the grayscale image
[Link](save_path) # Save the grayscale image
print(f"Grayscale image saved at: {save_path}")
except FileNotFoundError:
print("Error: The specified image file was not found. Please check the path.")
except UnidentifiedImageError:
print("Error: The file is not a valid image. Please provide a correct image file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")

# Replace 'path_to_your_image.jpg' and 'grayscale_image.png' with actual paths


image_path = input("Enter the path of the image to convert: ").strip()
save_path = input("Enter the path to save the grayscale image: ").strip()

convert_to_grayscale(image_path, save_path)

OUTPUT:

8
5. Write a python program to represent the data on the rating of mobile games
on bar chart. The sample data is given as: Pubg, Free Fire, Mine Craft, and GTA-V.
The rating for each game is as: 8.5, 7.8, 4.5, 9.7.

import [Link] as plt

games = ['Pubg', 'Free Fire', 'Mine Craft', 'GTA-V']


ratings = [8.5, 7.8, 4.5, 9.7]

[Link](games, ratings, color='blue')


[Link]('Games')
[Link]('Ratings')
[Link]('Mobile Games Ratings')
[Link]()

OUTPUT:

9
6. Write a python program to implement BFS for any graph.

from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])

while queue:
vertex = [Link]()
if vertex not in visited:
print(vertex)
[Link](vertex)
[Link](graph[vertex] - visited)

graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}

bfs(graph, 'A')

OUTPUT:

10
7. Write a python program to implement DFS for any graph.

def dfs(graph, start, visited=None):


if visited is None:
visited = set()

[Link](start)
print(start)

for next_vertex in graph[start] - visited:


dfs(graph, next_vertex, visited)

graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}

dfs(graph, 'A')

OUTPUT:

11
8. Implement a simple Hill Climbing algorithm for function optimization.
import random

def objective_function(x):
return -(x**2) + x + 10

def hill_climbing(starting_point):
current_point = starting_point
current_value = objective_function(current_point)

while True:
neighbors = [current_point + step for step in [-1, -0.5, -0.1, +0.1, +0.5, +1]]
next_point = max(neighbors, key=objective_function)
next_value = objective_function(next_point)

if next_value <= current_value:


break

current_point = next_point
current_value = next_value

return current_point

optimal_x = hill_climbing([Link](-10,10))
print("Optimal x:", optimal_x)

OUTPUT:

12
9. Implement the A* algorithm using a heuristic function for shortest path
finding.
from queue import PriorityQueue

def heuristic(a, b):


return abs(a[0] - b[0]) + abs(a[1] - b[1])

def get_neighbors(current, grid):


neighbors = []
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

for dr, dc in directions:


r, c = current[0] + dr, current[1] + dc
if 0 <= r < rows and 0 <= c < cols and grid[r][c] == 0:
[Link]((r, c))
return neighbors

def distance(a, b):


return 1

def astar(start, goal, grid):


open_set = PriorityQueue()
open_set.put((0, start))
came_from = {}

g_score = {start: float('inf')}


g_score[start] = 0

f_score = {start: float('inf')}


f_score[start] = heuristic(start, goal)

while not open_set.empty():


current = open_set.get()[1]

if current == goal:
return reconstruct_path(came_from, current)

for neighbor in get_neighbors(current, grid):


tentative_g_score = g_score[current] + distance(current, neighbor)

if tentative_g_score < g_score.get(neighbor, float('inf')):


came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
if not any(neighbor == item[1] for item in open_set.queue):
13
open_set.put((f_score[neighbor], neighbor))

return []

def reconstruct_path(came_from, current):


total_path = [current]
while current in came_from:
current = came_from[current]
total_path.append(current)
return total_path[::-1]

if __name__ == "__main__":

grid = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
]

start = (0, 0)
goal = (4, 4)

path = astar(start, goal, grid)


if path:
print("Path found:", path)
else:
print("No path found.")

OUTPUT:

14
10 . Write a program to represent knowledge using predicate logic and solve
queries.
class Predicate:
def __init__(self, name, *args):
[Link] = name
[Link] = args

def __str__(self):
return f"{[Link]}({', '.join(map(str, [Link]))})"

class KnowledgeBase:
def __init__(self):
[Link] = []

def add_fact(self, predicate):


[Link](predicate)

def query(self, predicate):


results = [fact for fact in [Link] if [Link] == [Link] and [Link] ==
[Link]]
return results

# Example Usage
if __name__ == "__main__":
kb = KnowledgeBase()

# Define some predicates


kb.add_fact(Predicate("Mammal", "Dog"))
kb.add_fact(Predicate("Mammal", "Cat"))
kb.add_fact(Predicate("Bird", "Sparrow"))
kb.add_fact(Predicate("HasWings", "Sparrow"))

# Query the knowledge base


query1 = Predicate("Mammal", "Dog")
query2 = Predicate("Bird", "Eagle")

# Check if Dog is a Mammal


if [Link](query1):
print(f"{query1} is known.")
else:
print(f"{query1} is not known.")
# Check if Eagle is a Bird
if [Link](query2):
print(f"{query2} is known.")
else:
print(f"{query2} is not known.")
15
OUTPUT:

12. Implement basic learning algorithm (Decision tree and frames).


from sklearn import tree

X = [[0, 0], [1, 1], [2, 2], [3, 3]]


Y = [0, 0, 1, 1]

clf = [Link]()
[Link](X, Y)

class Frame:
def __init__(self, features, prediction, rule_applied):
[Link] = features
[Link] = prediction
self.rule_applied = rule_applied

def display(self):
print(f"Features: {[Link]}")
print(f"Prediction: {[Link]}")
print(f"Rule Applied: {self.rule_applied}")

def create_frame(features, model):


prediction = [Link]([features])
rule_applied = "Based on decision tree rules"

return Frame(features, prediction[0], rule_applied)

frame = create_frame([1.5, 1.5], clf)


[Link]()

OUTPUT:

16
13. Write a python program that implements a simple rule-based system.
class RuleBasedSystem:
def __init__(self):
[Link] = {
"happy": "That's great! Keep up the positive vibes!",
"sad": "I'm sorry you're feeling this way. Try talking to a friend.",
"angry": "It's okay to feel angry, but take deep breaths and relax.",
"bored": "Try something new, maybe a hobby or a walk.",
"excited": "Awesome! Keep that energy going and channel it into something fun!"
}

def get_advice(self, mood):


"""Provides advice based on the user's mood"""
return [Link]([Link](), "Sorry, I don't have advice for that mood.")

def ask_user(self):
"""Asks the user for their mood and provides advice"""
mood = input("How are you feeling today? (happy, sad, angry, bored, excited): ").strip()
advice = self.get_advice(mood)
print(advice)

rule_based_system = RuleBasedSystem()
rule_based_system.ask_user()

OUTPUT:

17
14. Write a python program to perform basic text processing using a library like
SpeechRecognition.
import speech_recognition as sr

def listen_and_recognize():
# Initialize recognizer
recognizer = [Link]()
# Use the microphone as the source
with [Link]() as source:
print("Adjusting for ambient noise... Please wait.")
recognizer.adjust_for_ambient_noise(source)
print("Listening for speech... Speak now!")
# audio = [Link](source, timeout=5, phrase_time_limit=10)
audio= [Link](source)

try:
print("Recognizing...")
text = recognizer.recognize_google(audio)
print(f"You said: {text}")
except [Link]:
print("Sorry, I could not understand the audio.")
except [Link]:
print("Sorry, there was an error with the speech recognition service.")
listen_and_recognize()

OUTPUT:

18
15. Implement a basic neural network using python.
import numpy as np

class SimpleNeuralNetwork:

def __init__(self,input_size,layers_sizes):
self.layers_sizes= layers_sizes
[Link]= [[Link](layers_sizes[i-1], layers_sizes[i]) for i in
range(1,len(layers_sizes))]

def forward(self,x):
for weight in [Link]:
x= [Link]([Link](x ,weight))
return x

@staticmethod
def sigmoid(x):
return 1/(1+[Link](-x))

nn= SimpleNeuralNetwork(input_size=3,layers_sizes=[3 ,4 ,2])


output= [Link]([Link]([0.5 ,0.6 ,0.7]))
print(output)

OUTPUT:

19
16. Create an interactive question-answer expert system that takes user input
and provide expert advice.
class ExpertSystem:

def __init__(self):
# Expanded set of rules
[Link] = {
"unhealthy": ["eat fruits","avoid eating junk food", "exercise regularly", "get regular
checkups"],
"healthy": ["do follow your regular routine", "eat healthy food", "get enough sleep"],
"stressed": ["practice meditation", "take deep breaths", "talk to a friend"],
"sleepy": ["drink water", "take a short nap", "avoid caffeine before bedtime"],
"motivated": ["set clear goals", "stay organized", "take breaks when needed"],
"bored": ["try a new hobby", "read a book", "go for a walk"]
}

def ask_user(self):
user_input = input("How are you feeling? (healthy, unhealthy, stressed, sleepy, motivated,
bored): ").strip().lower()
advice = [Link](user_input)
if advice:
print(f"Advice: {', '.join(advice)}")
else:
print("No advice available. Please answer with 'healthy', 'unhealthy', 'stressed', 'sleepy',
'motivated', or 'bored'.")

expert_system = ExpertSystem()
expert_system.ask_user()

OUTPUT:

20
17. Write a python program to implement linear search algorithm.
def linear_search(arr,x):
for i in range(len(arr)):
if arr[i]== x:
return i
return -1

arr=[10 ,20 ,30 ,40 ,50]


x=int(input("Enter the element to be searched:"))

result= linear_search(arr,x)

if result != -1:
print(f"Element found at index {result}.")
else:
print("Element not found.")

OUTPUT:

21
18. Develop a simple text based game Stone paper scissors. Include game rules
and winning condition.
import random

def play_game():
choices=['rock','paper','scissors']

user_choice=input("Enter rock/paper/scissors: ").lower()

computer_choice=[Link](choices)

print(f"Computer chose: {computer_choice}")

if user_choice==computer_choice:
print("It's a tie!")

elif (user_choice=='rock' and computer_choice=='scissors') or \


(user_choice=='paper' and computer_choice=='rock') or \
(user_choice=='scissors' and computer_choice=='paper'):
print("You win!")

else:
print("You lose!")
play_game()

OUTPUT:

22
[Link] a python program where the computer randomly selects a number
between 1 to 100 and the player has to guess the number After each guess ,the
program should the tell the player whether the guess is too high or low.
import random

def guessing_game():
number=[Link](1 ,100)
chances=5

while chances:
chances=chances-1
guess=int(input("Guess the number between 1 and 100: "))

if guess<number:
print("Too low!")
elif guess>number:
print("Too high!")
else:
print("Congratulations! You guessed it right.")
break
print("Left Chances: ",chances)
if not chances:
print("Sorry! You have run out of chances. The number was", number)

guessing_game()

OUTPUT:

23
20. Create a python program that acts as a simple quiz game Ask the player
multiple choice question and keep track of their score.
questions=[
{
"question": "What is the largest planet in our solar system?",
"options": ["A) Earth", "B) Jupiter", "C) Saturn"],
"answer": "B"
},
{
"question": "What is the chemical symbol for water?",
"options": ["A) CO2", "B) O2", "C) H2O"],
"answer": "C"
},
{
"question": "Which continent is known as the 'Dark Continent'?",
"options": ["A) Asia", "B) Africa", "C) Europe"],
"answer": "B"
},
{
"question": "What is the speed of light in a vacuum?",
"options": ["A) 1,080,000 km/h", "B) 299,792 km/s", "C) 150,000 km/s"],
"answer": "B"
},
{
"question": "Who wrote 'Romeo and Juliet'?",
"options": ["A) William Shakespeare Mark Twain", "B) Mark Twain", "C) Jane Austen"],
"answer": "A"
},
{
"question": "Which gas is most abundant in the Earth's atmosphere?",
"options": ["A) Oxygen", "B) Nitrogen", "C) Argon"],
"answer": "B"
},
{
"question": "What is the main ingredient in guacamole?",
"options": ["A) Cilantro", "B) Lime", "C) Avocado"],
"answer": "C"
},
{
"question": "Which ocean is the largest?",
"options": ["A) Pacific ", "B) Arctic", "C) Atlantic"],
"answer": "A"
},
{
"question": "What is the square root of 64?",
"options": ["A) 6", "B) 10", "C) 8"],
24
"answer": "C"
},
{
"question": "Who is known as the 'Father of Computers'?",
"options": ["A) Alan Turing", "B) John von Neumann", "C) Charles Babbage"],
"answer": "C"
}
]

score=0

for q in questions:
print(q["question"])
for option in q["options"]:
print(option)

answer=input("Your answer (A/B/C): ").upper()

if answer==q["answer"]:
score+=1
print("Correct!\n")
else:
print(f"Wrong! The correct answer was {q['answer']}.\n")

print(f"Your final score is {score}/{len(questions)}.")

OUTPUT:

25

You might also like