Manual Python L2 Ad L9
Manual Python L2 Ad L9
interpreter
Aim:
To run python Script and various expressions in an interactive interpreter
a. Create a python program to enter two numbers and then performs and displays
the results of the following operations: addition, subtraction, multiplication, and
division.
Algorithm:
[Link].
[Link] the two numbers and store it in variable x and y.
[Link] Addition do ; x+y and print it.
[Link] Subtraction do ; x-y and print it.
[Link] Multiplication do ; x*y and print it.
[Link] Division do; x/y and print it.
[Link]
Program:
x =int(input("Enter the First number:"))
y =int(input("Enter the Second number:"))
add = x + y
sub = x - y
pro = x * y
div = x / y
print("Addition:",add)
print("Subtraction :",sub)
print("Multiplication:",pro)
print("Division:",div)
Output:
b. Create a python program to enter two numbers and then performs and displays
the results of the following relational expression : >, <, ==, !=, >=, <=
Algorithm:
[Link]
[Link] the the input from the user and store it in a,b&c.
[Link] the relational operations( i.e, >,<.=,==,!=,>=,<=).
[Link] the results.
[Link].
Program:
Output:
c. Create a python program to enter three numbers and then performs and displays
the results of the following Logical operations: and, or, not.
Algorithm:
[Link].
[Link] the input from the user.
[Link] the logical operations on the inputs.
[Link] the results.
[Link].
Program:
# Taking three numbers as input
a = int(input("Enter the First number: "))
b = int(input("Enter the Second number: "))
c = int(input("Enter the Third number: "))
Output
Result
Thus, the python program to run Python Script and various expressions in an
interactive interpreter was don successfully and the output was verified.
Task 2: Implement conditional, control and looping statements
AIM
a. You are developing a simple grade management system for a school. The
system needs to determine the grade of a student based on their score in a
test. The grading system follows these rules:
ALGORITHM
1. Start
2. Get the input mark from the user.
3. With the use of an If-elif-else statement do
• If the marks>=90 print grade “A”.
• If the mark is between 80 and 89 print grade “B”.
• If the mark is between 70 and 79 print grade “C”.
• If the mark is between 60 and 69 print grade “D”.
• If the mark is below 60, print grade “F”.
4. Stop
PROGRAM
if score>=90:
else:
Output:
b. You are developing an educational program to help young students learn about
natural numbers. One of the features of the program is to display the first 10
natural numbers to the user. Write a Python program that uses a for loop to
print the first 10 natural numbers.
ALGORITHM
[Link].
[Link]
PROGRAM
# Displaying the first 10 natural numbers
print(i)
Output:
c. You are working on a feature for a financial application that involves validating
user input. One of the requirements is to count the total number of digits in a
given number
ALGORITHM
[Link].
PROGRAM
count=len(string)
Task 2
2.1 Develop a simple program for the Air Force to label an aircraft as military of civilian.
The program is to be given the plane’s observed speed in km/h (kilometer per hour). The
speed will serve as its input. For planes traveling in excess of 1100 km/h, you should display
them as “ It’s a civilian aircraft”, between 500 km/h to 1100 km/h, display them as “ It’s a
military aircraft!” and for planes traveling at more slower speed – less than 500 km/h, you
should display them as an “ It’s a BIRD!”.
2.2 The National Earthquake Information Center has the following criteria to determine the
earthquake’s damage. Here are the given richter scale criteria and their corresponding
characterization. The richter scale serves as the input data and the characterization as output
information. Use the ladderized if / else if / else conditional statement.
Richter Numbers (n) Characterization
n<5.0 Little or no damage
5.0>=n<5.5 Some damage
5.5>=n<6.5 Serious damage
6.5>=n<7.5 Disaster
higher Catastrophe
Input & Output:
2
6
Serious damage
2
Little or no damage
RESULT
Aim:
Algorithm:
1. Define functions for addition, subtraction, multiplication, and division.
Program:
import mymath
a = 10
b=5
print("Addition:", [Link](a, b))
print("Subtraction:", [Link](a, b))
print("Multiplication:", [Link](a, b))
print("Division:", [Link](a, b))
Output:
b. You are working on a Python project that requires you to perform various
mathematical operations and geometric area calculations. To organize your
code better, you decide to create a package named mypackage which
includes sub packages pack1 and pack 2 with two modules: mathfunctions
and areafunctions Demonstrate the use of the functions by performing a few
calculations and printing the results.
Algorithm:
1. Create [Link] module:
2. Create [Link] module:
4. Create [Link]:
Program:
1. Create the [Link] module
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error! Division by zero."
return a / b
Output:
Result:
Thus, the program for Importing Python modules and packages was successfully
executed and the output was verified.
Task 4. Use various data types, List, Tuples and Dictionary in python
programming
Aim:
To use various data types, List, Tuples and Dictionary in python programming
a. You are working on a Python project that requires you to manage and
manipulate a list of numbers. Your task is to create a Python program that
demonstrates the following list operations:
ALGORITHM
1. Start
2. For adding elements to a list first create a list with name “list” and assign the
values within [] brackets , inorder to add a new value use the function
append().
3. For removing a specific element use “pop(index value)” or
“remove(itemname)”.
4. For sorting the elements use “sorted(list)” function.
5. For finding minimum value use “min(list)” and for maximum use “max(list)”.
6. For sum use function “sum(list)” and for average use the formula
“sum(list)/len(list)”
7. Print the output.
8. End.
PROGRAM
[Link](a)
print(list)
#Remove Elements: Remove specific elements from the list.
[Link](1)#by index value
print(list)
[Link](10)#by itemname
print(list)
#Sort Elements: Sort the list in ascending and descending order.
l=[5,8,9,15,30,89]
print(sorted(l))
#Find Minimum and Maximum: Find the minimum and maximum elements in thelist.
print("The minimum value is:",min(l))
print("The maximum value is:",max(l))
#Calculate Sum and Average
print("The sum is:",sum(l))
print("The average is :",((sum(l)/len(l))))
OUTPUT
b. You are tasked with creating a Python program that showcases operations
on tuples. Tuples are immutable sequences, similar to lists but with the key
difference that they cannot be changed after creation. Your program should
illustrate the following tuple operations:
1. Create a Tuple: Define a tuple with elements of different data types(10,
'hello', 3.14, 'world')
2. Access Elements: Access individual elements and slices of the tuple.
3. Concatenate Tuples: Combine two tuples to create a new tuple.
4. Immutable Nature: Attempt to modify elements of the tuple and handle the
resulting error.
ALGORITHM
1. Start.
2. To create a tuple use “tuple_name=(values)”.
3. To access the elements of a tuple either use the index values (
tuple_name(index_value)) or the tuple slicing ( tuple_name[start:end]).
4. To concatenate tuples use the operator “+” (tuple1 “+” tuple2).
5. Try to modify the tuple elements by assigning the values directly like ;
tuple(index)= new_value , will result in an error as it is immutable.
6. Print the output.
7. End.
PROGRAM
#Create a Tuple: Define a tuple with elements of different data types(10, 'hello',
3.14, 'world')
tuple=(10, 'hello', 3.14, 'world')
print(tuple)
#Access Elements: Access individual elements and slices of the tuple.
for i in tuple:
print(i)
print(tuple[1:3])
print(tuple[:-1])
#Concatenate Tuples: Combine two tuples to create a new tuple.
t2=(5,0.5)
t3=tuple+t2
print(t3)
#Immutable Nature: Attempt to modify elements of the tuple and handle the
resulting error.
tuple(3)="PI" #ERROR
OUTPUT
c. You are tasked with creating a Python program that showcases operations
on dictionaries. Dictionaries in Python are unordered collections of items.
Each item is a pair consisting of a key and a value. Your program should
illustrate the following dictionary operations:
Algorithm
#Modify Dictionary: Update values, add new key-value pairs, and remove
existing pairs.
dictionary['name']= "James"
print(dictionary)
[Link]('city')
print(dictionary)
#Iterate Over Dictionary: Use loops to iterate over keys or values.
for k in dictionary:
print("KEY:",k)
print([Link]())
OUTPUT
RESULT
Thus, various data types, List, Tuples and Dictionary in python programming was
used and verified successfully.
Aim:
To Implement various Searching and Sorting Operations in python
programming.
Program 5.1
def find_employee_by_id(employees, target_id):
for employee in employees:
if employee['id'] == target_id:
return employee
return None
Output:
5.2. You are developing a grade management system for a school. The system
maintains a list of student records, where each record is represented as a
dictionary containing a student's name and score. The school needs to generate a
report that displays students' scores in ascending order. Your task is to implement
a feature that sorts the student records by their scores using the Bubble Sort
algorithm.
Algorithm:
[Link]:
• Get the length of the students list and store it in n.
[Link] Loop:
• Iterate from i = 0 to n-1 (inclusive). This loop represents the number of passes
through the list.
3. Track Swaps:
• Initialize a boolean variable swapped to False. This variable will track if any
swaps are made in the current pass.
4. Inner Loop:
• Iterate from j = 0 to n-i-2 (inclusive). This loop compares adjacent elements in
the list and performs swaps if necessary.
5. Compare and Swap:
• For each pair of adjacent elements (i.e., students[j] and students[j+1]):
Program 5.2
def bubble_sort_scores(students):
n = len(students)
for i in range(n):
# Track if any swap is made in this pass
swapped = False
for j in range(0, n-i-1):
if students[j]['score'] > students[j+1]['score']:
# Swap if the score of the current student is greater than the next
students[j], students[j+1] = students[j+1], students[j]
swapped = True
# If no two elements were swapped, the list is already sorted
if not swapped:
break
# Example usage
students = [
{'name': 'Alice', 'score': 88},
{'name': 'Bob', 'score': 95},
{'name': 'Charlie', 'score': 75},
{'name': 'Diana', 'score': 85}
]
print("Before sorting:")
for student in students:
print(student)
bubble_sort_scores(students)
print("\nAfter sorting:")
for student in students:
print(student)
Output:
Result:
Thus, the Program for various Searching and Sorting Operations is executed and
verified successfully.
Aim:
To write a python program Implement various text file operations
Problem 6.1:
You need to write the sentence "Error objects are thrown when runtime errors occur.
The Error object can also be used as a base object for user-defined exceptions" into a
text file named [Link]. Implement a function that performs this task.
Algorithm:
1. Write to a File:
o Define writefile(filename) function:
▪ Open a file named "[Link]" in write mode.
▪ Write the following text to the file:
▪ "Error objects are thrown when runtime errors occur. The
Error object can also be used as a base object for user-
defined exceptions"
▪ Close the file.
2. Read from a File:
o Define readfile(filename) function:
▪ Open the file specified by filename in read mode using a with
statement.
▪ Read the entire content of the file.
▪ Print the content.
3. Execute the Program:
o Call writefile("write") to write the predefined text to "[Link]".
o Call readfile("text") to attempt to read from a file named "text" and print
its content.
Program 6.1
def writefile(filename):
f=open("[Link] ","w")
[Link]("Error objects are thrown when runtime errors occur. The Error object
can also be used as a base object for user-defined exceptions ")
[Link]()
def readfile(filename):
with open(filename, "r") as file:
content = [Link]()
print(content)
writefile("write")
readfile("text")
Output:
Problem 6.2.
You have a text file [Link] containing logs of a system. Write a function that counts the
number of lines containing the word "ERROR".
Algorithm:
1. Initialize Error Counter:
o Define the function count_error_lines(filename):
▪ Initialize error_count to 0.
2. Open and Read File:
o Open the file specified by filename in read mode using a with statement.
3. Check Each Line for "ERROR":
o Loop through each line in the file:
▪ If the line contains the word "ERROR", increment error_count by 1.
4. Return Error Count:
o After reading all the lines, return the value of error_count.
5. Execute the Program:
o Call count_error_lines("[Link]") to count the number of lines with the
word "ERROR" in the file "[Link]".
o Print the result with the message: "Number of lines with 'ERROR':
{error_lines}".
Program 6.3:
def count_error_lines(filename):
error_count = 0
with open(filename, "r") as file:
for line in file:
if "ERROR" in line:
error_count += 1
return error_count
error_lines = count_error_lines("[Link]")
print(f"Number of lines with 'ERROR': {error_lines}")
[Link]
“Error objects are thrown when runtime Error occur.
The Error object can also be used as a base object for user-defined exceptions.”
Output:
Problem 6.3:
You need to write a report containing the details (Name, departments) of the employee
in list. Write a Python function that writes this report to a file named
employee_report.txt
Algorithm:
1. Create Employee Data:
o Define the function write_employee_report(filename):
▪ Create a list employees containing dictionaries, each with "name"
and "department" keys for individual employees.
2. Open File for Writing:
o Open the file specified by filename in write mode using a with statement.
3. Write Employee Data to File:
o Loop through each employee in the employees list:
▪ For each employee, format a string as "Name: {employee['name']},
Department: {employee['department']}".
▪ Write the formatted string to the file, followed by a newline
character (\n).
4. Execute the Program:
o Call write_employee_report("employee_report.txt") to write the employee
data to the file "employee_report.txt".
Program 6.3:
def write_employee_report(filename):
employees = [
{"name": "Alice", "department": "HR"},
{"name": "Bob", "department": "Engineering"},
{"name": "Charlie", "department": "Finance"}
]
# Example usage:
write_employee_report("employee_report.txt")
output:
Result:
Thus, the python program Implement various text file operations was
successfully executed and the output was verified.
Aim:
To write the python program using ‘Functions’ concepts in Python Programming
7.1. You are developing a small Python script to analyze and manipulate a list of
student grades for a class project. Write a Python program that satisfies the above
requirements using the built-in functions print(), len(), type(), max(), min(),
sorted(), reversed(), and range().
Algorithm:
1. Start the program
2. Print a welcome message: Outputs a simple greeting.
3. Determine and print the number of students: Uses len() to find the number of
elements in the student_names list.
4. Print the type of lists: Uses type() to show the type of the student_names and
student_grades lists.
5. Find and print highest and lowest grades: Uses max() and min() to determine the
highest and lowest values in student_grades.
6. Print sorted list of grades: Uses sorted() to sort the grades.
7. Print reversed list of grades: Uses reversed() to reverse the sorted list and
converts it to a list.
8. Generate and print a range of grade indices: Uses range() to create a list of
indices from 1 to the number of students.
9. Stop
Program:
def analyze_student_grades():
# Sample data
student_names = ["Alice", "Bob", "Charlie", "Diana"]
student_grades = [85, 92, 78, 90]
# 3. Print the type of the student names list and the grades list
print("\nType of student_names list:", type(student_names))
print("Type of student_grades list:", type(student_grades))
# 7. Generate and print a range of grade indices from 1 to the number of students
grade_indices = list(range(1, num_students + 1))
print("\nGrade indices from 1 to number of students:", grade_indices)
Output:
7.2. You are tasked with creating a small calculator application to help users
perform basic arithmetic operations and greet them with a personalized message.
Your application should perform the following tasks: addition, subtraction,
multiplication, division.
Algorithm:
1. Start the program
2. User Input for Numbers: The program prompts the user to enter two numbers.
3. User Input for Operation: The program prompts the user to choose an arithmetic
operation (addition, subtraction, multiplication, division).
4. Perform Operation: Based on the user's choice, the program performs the chosen
arithmetic operation using the defined functions.
5. Display Result: The program displays the result of the operation.
6. Stop
[Link]:
def add(a, b):
"""Return the sum of two numbers."""
return a + b
def subtract(a, b):
"""Return the difference between two numbers."""
return a - b
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
def divide(a, b):
"""Return the quotient of two numbers. Handles division by zero."""
if b != 0:
return a / b
else:
return "Error: Division by zero"
def greet(name):
"""Return a greeting message for the user."""
return f"Hello, {name}! Welcome to the program."
def main():
# Demonstrating the use of user-defined functions
# Arithmetic operations
num1 = 10
num2 = 5
print("Arithmetic Operations:")
print(f"Sum of {num1} and {num2}:", add(num1, num2))
print(f"Difference between {num1} and {num2}:", subtract(num1, num2))
print(f"Product of {num1} and {num2}:", multiply(num1, num2))
print(f"Quotient of {num1} and {num2}:", divide(num1, num2)
# Greeting the user
user_name = "Alice"
print("\nGreeting:")
print(greet(user_name))
Output:
Result:
Thus, the python program using ‘Functions’ concepts was successfully executed
and the output was verified.
Task [Link] python generator and decorators CO1-K3
Aim:
Write a python program to Implement python generator and decorators
Produce a sequence of numbers when provided with start, end, and step values.
Algorithm:
1. Define Generator Function:
o Define the function number_sequence(start, end, step=1).
2. Initialize Current Value:
o Set current to the value of start.
3. Generate Sequence:
o While current is less than or equal to end:
▪ Yield the current value of current.
▪ Increment current by step.
4. Get User Input:
o Read the starting number (start) from user input.
o Read the ending number (end) from user input.
o Read the step value (step) from user input.
5. Create Generator Object:
o Create a generator object by calling number_sequence(start, end, step)
with user-provided values.
6. Print Generated Sequence:
o Iterate over the values produced by the generator object.
o Print each value.
8.1. Program:
def number_sequence(start, end, step=1):
current = start
while current <= end:
yield current
current += step
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
step = int(input("Enter the step value: "))
# Create the generator
sequence_generator = number_sequence(start, end, step)
# Print the generated sequence of numbers
for number in sequence_generator:
print(number)
Output:
Enter the starting number: 1
Enter the ending number: 50
Enter the step value: 5
1
6
11
16
21
26
31
36
41
46
Produce a default sequence of numbers starting from 0, ending at 10, and with a
step of 1 if no values are provided.
Algorithm:
1. Start Function:
o Define the function my_generator(n) that takes a parameter n.
2. Initialize Counter:
o Set value to 0.
3. Generate Values:
o While value is less than n:
▪ Yield the current value.
▪ Increment value by 1.
4. Create Generator Object:
o Call my_generator(11) to create a generator object.
5. Iterate and Print Values:
o For each value produced by the generator object:
▪ Print value.
8.1.(b)Program:
def my_generator(n):
# initialize counter
value = 0
# loop until counter is less than n
while value < n:
# produce the current value of the counter
yield value
# increment the counter
value += 1
# iterate over the generator object produced by my_generator
for value in my_generator(3):
# print each value produced by generator
print(value)
Output:
0
1
2
Algorithm:
1. Create Decorators:
o Define uppercase_decorator to convert the result of a function to
uppercase.
o Define lowercase_decorator to convert the result of a function to
lowercase.
2. Define Functions:
o Define shout function to return the input text. Apply
@uppercase_decorator to this function.
o Define whisper function to return the input text. Apply
@lowercase_decorator to this function.
3. Define Greet Function:
o Define greet function that:
▪ Accepts a function (func) as input.
▪ Calls this function with the text "Hi, I am created by a function
passed as an argument."
▪ Prints the result.
4. Execute the Program:
o Call greet(shout) to print the greeting in uppercase.
o Call greet(whisper) to print the greeting in lowercase.
Program:
def uppercase_decorator(func):
def wrapper(text):
return func(text).upper()
return wrapper
def lowercase_decorator(func):
def wrapper(text):
return func(text).lower()
return wrapper
@uppercase_decorator
def shout(text):
return text
@lowercase_decorator
def whisper(text):
return text
def greet(func):
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
Result:
Thus the python program to Implement python generator and decorators was
successfully executed and the output was verified.
Task 9: Implement Exceptions and Exceptional handling in Python.
Aim:
Problem [Link] are developing a Python program that processes a list of students'
grades. The program is designed to allow the user to select a grade by specifying an
index number. However, you need to ensure that the program handles cases where
the user inputs an index that is out of range, i.e., an index that does not exist in the
list.
Algorithm:
1. Start the program
2. Initializes a list of grades (e.g., [85, 90, 78, 92, 88]).
3. Prompts the user to enter the index of the grade they wish to view.
4. Attempts to display the grade at the specified index.
5. If the index is out of range, catches the IndexError and prints an error message,
"Invalid index. Please enter a valid index."
Program:
# Initialize the list of grades
grades = [85, 90, 78, 92, 88]
# Prompt the user to enter the index of the grade they want to view
try:
index = int(input("Enter the index of the grade you want to view: "))
# Attempt to display the grade at the specified index
print(f"The grade at index {index} is: {grades[index]}")
except IndexError:
# Handle the case where the index is out of range
print("Invalid index. Please enter a valid index.")
except ValueError:
# Handle the case where the input is not an integer
print("Invalid input. Please enter a numerical index.")
Output:
Problem 9.2. You are developing a Python calculator program that performs basic
arithmetic operations. One of the key functionalities is to divide two numbers
entered by the user. However, dividing by zero is not allowed and would cause the
program to crash if not handled properly.
Algorithm:
Program:
Output:
Algorithm:
1. Define the custom exception.
2. Prompt the user for input.
3. Check if the age is below 18.
4. Raise an exception if the condition is met.
5. Handle the exception with a custom error message.
Program:
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
# you need to guess this number
number = 18
try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")
except InvalidAgeException:
print("Exception occurred: Invalid Age")
Output:
Enter a number: 15
Exception occurred: Invalid Age
Result:
Thus the program for Implement Exceptions and Exceptional handling is
executed and verified successfully
Aim:
To use Matplotlib module for plotting in python.
Problem 10.1. Write a Python programming to display a bar chart of the popularity
of programming Languages.
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Sample Output:
Algorithm:
1. Define two lists for programming languages and their popularity respectively
2. Find the maximum popularity value in the list
3. Define a scaling factor to scale the bar heights within a certain limit (e.g. 50
characters)
4. For each language and popularity pair, calculate the bar height as the popularity
value scaled by the scaling factor
5. Print the chart using a loop to iterate over the programming language list: a.
Print the language name and a separator character (e.g. "|") b. Use a loop to print
the bar chart by printing the bar character (e.g. "*") a number of times equal to
the bar height c. Print the popularity value with a separator character d. Print a
newline character
Program:
#pip install matplotlib
import [Link] as plt
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Sample Output:
Algorithm:
1. Create a list of Programming Languages and Popularity
2. Create a pie chart using the matplotlib library
3. Set the title and legend for the pie chart
4. Show the pie chart
Program:
import [Link] as plt
# Step 1
languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
# Step 2
[Link](popularity, labels=languages, autopct='%1.1f%%')
# Step 3
[Link]('Popularity of Programming Languages')
[Link](languages, loc="best")
# Step 4
[Link]()
Output:
Result: Thus the python program use Matplotlib module for plotting is executed and
verified successful.
Aim:
To use Tkinter module for UI design
Problem 11.1. Write a Python GUI program to create a label and change the label
font style (font name, bold, size) using tkinter module.
Algorithm:
1. Import tkinter module
2. Create a main window
3. Create a label with desired text
4. Add the label to the main window using pack() method
5. Define a function to change font style
6. Create a button to call the function when clicked
7. Add the button to the main window using pack() method
8. Start the main loop.
Program:
import tkinter as tk
Task 11.2: Write a Python GUI program to create three single line text-box to
accept a value from the user using tkinter module.
Algorithm:
1. Import the tkinter module
2. Create the main window
3. Add labels and text-boxes to the main window
4. Set the size of the text-boxes
5. Create a button to submit the values entered in the text-boxes
6. Get the values entered in the text-boxes when the button is clicked
7. Close the main window when the button is clicked
Program:
import tkinter as tk
[Link](width=30)
Output:
Result: Thus the Program using Tkinter module for UI design was executed and verified
successfully.
SnakeGame:
Conditions:
[Link] the window size
[Link] a snake
[Link] the snake to move in the directions when left,right,down and up key is pressed
[Link] the snake hits the [Link] the score by 10
[Link] the snake hits the [Link] over
Sample Output:
Algorithm:
1. Import pygame package and initialize it
2. Define the window size and title
3. Create a Snake class which initializes the snake position, color, and movement
4. Create a Fruit class which initializes the fruit position and color
5. Create a function to check if the snake collides with the fruit and increase the
score
6. Create a function to check if the snake collides with the window and end the
game
7. Create a function to update the snake position based on the user input
8. Create a function to update the game display and draw the snake and fruit
9. Create a game loop to continuously update the game display, snake position, and
check for collisions
10. End the game if the user quits or the snake collides with the window
Program:
# importing libraries
import pygame
import time
import random
snake_speed = 15
# Window size
window_x = 720
window_y = 480
# defining colors
black = [Link](0, 0, 0)
white = [Link](255, 255, 255)
red = [Link](255, 0, 0)
green = [Link](0, 255, 0)
blue = [Link](0, 0, 255)
# Initialising pygame
[Link]()
fruit_spawn = True
# initial score
score = 0
# displaying Score function
def show_score(choice, color, font, size):
# displaying text
game_window.blit(score_surface, score_rect)
# Main Function
while True:
if not fruit_spawn:
fruit_position = [[Link](1, (window_x//10)) * 10,
[Link](1, (window_y//10)) * 10]
fruit_spawn = True
game_window.fill(black)
Output
Sample output:
Algorithm:
1. Import pygame and initialize it.
2. Set screen size and title.
3. Define colors for the board and pieces.
Define a function to draw the board by looping over rows and columns and
drawing squares of different colors.
4. Define a function to draw the pieces on the board by loading images for each
piece and placing them on the corresponding square.
5. Define the initial state of the board as a list of lists containing the pieces.
6. Draw the board and pieces on the screen.
7. Start the game loop.
Program:
import pygame
# Initialize pygame
[Link]()
# Define colors
black = (0, 0, 0)
white = (255, 255, 255)
brown = (153, 76, 0)
Output:
Result:
Thus the program for pygame is executed and verified successfully.