Python Record 2025
Python Record 2025
Write a Python program to compute the areas of a triangle and a circle using user-provided inputs.
Task 1: Calculate the Area of a Triangle
● Use the input() function to ask the user to enter the base of the triangle.
● Use the input() function again to ask for the height of the triangle.
● Convert these inputs into floating-point numbers using float() since the inputs are strings
by default.
● Use the formula 0.5 * base * height to compute the area of the triangle.
● Use the print() function to output the computed area of the triangle with a descriptive
label (e.g., "The area of the triangle is:").
Task 2: Calculate the Area of a Circle
● Use the input() function to ask the user to enter the radius of the circle.
● Convert this input into a floating-point number using float().
● Use the formula 3.14 * radius ** 2 to compute the area of the circle.
● Use the print() function to output the computed area of the circle with a descriptive label
(e.g., "The area of the circle is:").
1
TO CALCULATE AREA OF SHAPES
AIM :
To write a Python program to compute the areas of a triangle and a circle using user-provided
inputs.
ALGORITHM:
Calculating the Area of a Triangle:
Step 1: Start the program.
Step 2: Prompt the user to input the base of the triangle using the input() function. Store the
input in a variable called base.
Step 3: Convert the base input to a floating-point number using the float() function.
Step 4: Prompt the user to input the height of the triangle using the input() function. Store the
input in a variable called height.
Step 5: Convert the height input to a floating-point number using the float() function.
Step 6: Compute the area of the triangle using formula Area = 0.5 * base * height
Step 7: Output the computed area of the triangle with a descriptive message, e.g., "The area of
the triangle is:"
Step 8: End the program.
Calculating the Area of a Circle:
Step 1: Start the program.
Step 2: Prompt the user to input the radius of the circle using the input()function.
Store the input in a variable called radius.
Step 3: Convert the radius input to a floating-point number using float()function.
Step 4: Compute the area of the circle using the formula:
Area = 3.14 * radius^2
Step 5: Output the computed area of the circle with a descriptive message,e.g., "The area of
the circle is:"
Step 6: End the program.
2
CODING:
# Task 1: Calculate the Area of a Triangle
# Ask the user to input the base of the triangle
OUTPUT:
Enter the height of the triangle:108
Enter the base of the triangle:97
('The area of the triangle is:', 5238.0)
3
# Task 2: Calculate the Area of a Circle
# Ask the user to input the radius of the circle
radius = float(input("Enter the radius of the circle: "))
# Calculate the area of the circle using the formula: 3.14 * radius^2
circle_area = 3.14 * radius ** 2
# Output the area of the circle with a descriptive label
print("The area of the circle is:”,circle_area)
OUTPUT:
Enter the radius of the circle:108
('The area of circle', 36624.96)
RESULT:
Thus the above programs has been executed and verified successfully.
4
EX. NO: 2 EXPLORING STRINGS, VARIABLES, AND COMMENTS
Write a Python program that demonstrates working with strings, variable assignments, and uses
comments to explain the code.
Task 1: Working with Strings
Create a string variable to store your full name.
Print the string to display your full name on the console.
Slice the string to print the first 3 characters of your full name.
Concatenate another string (e.g., a nickname or a title) to your full name and print the
new string.
Task 2: Assignments in Python
Assign values to variables representing your age and height. For example, age could be
25 and height could be 5.9.
Assign the value of your height to another variable (e.g., height_in_meters), then print the
value of this new variable.
Modify the value of one of the variables (e.g., update age) and print the updated value.
Task 3: Using Comments
Create a simple Python program that calculates the sum of two numbers.
Add comments before each line of code to describe what that line does (e.g., "This
line adds two numbers & quot;).
Add a comment at the beginning of the program to explain its purpose (e.g., "This
program calculates the sum of two numbers & quot;).
5
EXPLORING STRINGS, VARIABLES, AND COMMENTS
AIM:
To write a Python program that demonstrates working with strings, variable assignments, and
uses comments.
ALGORITHM:
Step 1: Create a string variable to store your full name. Example: full_name = "John Doe"
Step 2: Print the string to display your full name on the console.
Step 3: Slice the string to print the first 3 characters of your full name.
Step 4: Concatenate another string (e.g., a nickname) to your full name and print the new
string.
Step 6: Assign the value of your height to another variable (e.g., height_in_meters).
Convert height from feet to meters: height_in_meters = height * 0.3048.Use:
print("Height in Meters:", height_in_meters)
Step 7: Modify the value of one of the variables (e.g., update age) and print the updated value.
Step 8: Add a comment at the beginning of the program to explain its purpose.
6
# Task 1: Working with Strings
# Creating a string variable to store my full name
full_name = "John Doe"
# Slicing the string to print the first 3 characters of the full name
print("First 3 Characters:", full_name[:3])
# Concatenating another string (e.g., a nickname) to the full name and printing the new
string
nickname = " - Johnny"
full_name_with_nickname = full_name + nickname
print("Full Name with Nickname:", full_name_with_nickname)
7
# Calculating the sum of the two numbers
sum_result = num1 + num2
8
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
9
EX. NO: 3 BASIC DEMONSTRATION OF PYTHON DATA TYPES AND EXPRESSIONS
Write a Python program that demonstrates the use of various data types, character sets, and
expressions.
Task 1: Working with Different Data Types
Create a string variable and print it.
Create an integer variable, perform an arithmetic operation, and print the result.
Create a float variable, perform a mathematical operation, and print the result.
Create a boolean variable and print it.
Create a list variable, add items to it, and print it.
Task 2: Character Sets
Display the ASCII value of a character using Python’s built-in ord() function.
Convert an ASCII value back to its character using Python’s built-in chr() function.
Task 3: Expressions
Create a mathematical expression using operators (e.g., addition, subtraction,
multiplication).
Use comparison operators to compare two values.
Use logical operators (and, or, not) to create boolean expressions.
10
BASIC DEMONSTRATION OF PYTHON DATA TYPES AND EXPRESSIONS
AIM:
To write a Python program that demonstrates the use of various data types, character sets, and
expressions.
ALGORITHM:
Task 1: Working with Different Data Types
Task 3: Expressions
Step 8: Create a mathematical expression using operators and print the result.
Step 9: Compare two values using comparison operators and print the result.
Step 10: Create a boolean expression using logical operators and print the result.
11
CODING:
# Creating an integer variable, performing an arithmetic operation, and printing the result
age = 30
age_next_year = age + 1 # Adding 1 to the current age
print("Integer operation result (age next year):", age_next_year)
# Creating a float variable, performing a mathematical operation, and printing the result
height = 5.7 # Height in feet
height_in_inches = height * 12 # Converting height to inches
print("Float operation result (height in inches):", height_in_inches)
12
# Task 3: Expressions
# Creating a mathematical expression using operators
num1, num2 = 15, 10
expression_result = (num1 + num2) * (num1 - num2)
print("Mathematical expression result:", expression_result)
13
OUTPUT:
('String:', 'Alice')
('Integer operation result (age next year):', 31)
('Float operation result (height in inches):', 68.4)
('Boolean value:', False)
('List:', ['Apple', 'Banana', 'Cherry'])
('ASCII value of', 'A', 'is:', 65)
('Character for ASCII value 66 is:', 'B')
('Mathematical expression result:', 125)
('Comparison (num1 > num2):', True)
('Logical expression result:', True)
RESULT:
Thus the above program has been executed and verified successfully.
14
EX. NO: 4 MINUTES IN A YEAR CALCULATOR
AIM:
To write a Python program that calculates the number of minutes in a year.
ALGORITHM:
Step 4: Multiply the number of days in a year, hours in a day, and minutes in an hour to
calculate the total number of minutes.
15
CODING:
16
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
17
EX. NO: 5 DISPLAY ASCII VALUES AND CHARACTERS
18
DISPLAY ASCII VALUES AND CHARACTERS
AIM:
To write a Python program that display ascii values and characters.
ALGORITHM:
Task 1: Print the First 128 ASCII Values and Corresponding Characters
Step 1: Use a loop to iterate through the first 128 ASCII values (0 to 127).
Step 2: For each value in the loop, print the ASCII value and the corresponding character using chr().
Task 2: Print Each Character of a Given String Along with Its ASCII Value
Step 5: For each character, print the character and its corresponding ASCII value using the ord().
19
CODING:
# Task 1: Print the First 128 ASCII Values and Corresponding Characters
print("First 128 ASCII Values and Their Corresponding Characters:")
# Loop through ASCII values from 0 to 127
for ascii_value in range(128):
# Use commas for concatenation
print("ASCII Value:", ascii_value, "-> Character:", chr(ascii_value))
print("\n") # Adding a line break for better readability
# Task 2: Print Each Character of a Given String Along with Its ASCII Value
# Assume the variable `testString` refers to a string
testString = "Python Programming!"
# Properly format the f-string
print("Characters and ASCII Values for the string:", testString)
# Loop through each character in the string
for char in testString:
# Use commas for concatenation
print("Character:", char, "-> ASCII Value:", ord(char))
20
OUTPUT:
21
('ASCII Value:', 32, '-> Character:', ' ')
('ASCII Value:', 33, '-> Character:', '!')
('ASCII Value:', 34, '-> Character:', '"')
('ASCII Value:', 35, '-> Character:', '#')
('ASCII Value:', 36, '-> Character:', '$')
('ASCII Value:', 37, '-> Character:', '%')
('ASCII Value:', 38, '-> Character:', '&')
('ASCII Value:', 39, '-> Character:', "'")
('ASCII Value:', 40, '-> Character:', '(')
('ASCII Value:', 41, '-> Character:', ')')
('ASCII Value:', 42, '-> Character:', '*')
('ASCII Value:', 43, '-> Character:', '+')
('ASCII Value:', 44, '-> Character:', ',')
('ASCII Value:', 45, '-> Character:', '-')
('ASCII Value:', 46, '-> Character:', '.')
('ASCII Value:', 47, '-> Character:', '/')
('ASCII Value:', 48, '-> Character:', '0')
('ASCII Value:', 49, '-> Character:', '1')
('ASCII Value:', 50, '-> Character:', '2')
('ASCII Value:', 51, '-> Character:', '3')
('ASCII Value:', 52, '-> Character:', '4')
('ASCII Value:', 53, '-> Character:', '5')
('ASCII Value:', 54, '-> Character:', '6')
('ASCII Value:', 55, '-> Character:', '7')
('ASCII Value:', 56, '-> Character:', '8')
('ASCII Value:', 57, '-> Character:', '9')
('ASCII Value:', 58, '-> Character:', ':')
('ASCII Value:', 59, '-> Character:', ';')
('ASCII Value:', 60, '-> Character:', '<')
('ASCII Value:', 61, '-> Character:', '=')
('ASCII Value:', 62, '-> Character:', '>')
('ASCII Value:', 63, '-> Character:', '?')
('ASCII Value:', 64, '-> Character:', '@')
('ASCII Value:', 65, '-> Character:', 'A')
('ASCII Value:', 66, '-> Character:', 'B')
22
('ASCII Value:', 67, '-> Character:', 'C')
('ASCII Value:', 68, '-> Character:', 'D')
('ASCII Value:', 69, '-> Character:', 'E')
('ASCII Value:', 70, '-> Character:', 'F')
('ASCII Value:', 71, '-> Character:', 'G')
('ASCII Value:', 72, '-> Character:', 'H')
('ASCII Value:', 73, '-> Character:', 'I')
('ASCII Value:', 74, '-> Character:', 'J')
('ASCII Value:', 75, '-> Character:', 'K')
('ASCII Value:', 76, '-> Character:', 'L')
('ASCII Value:', 77, '-> Character:', 'M')
('ASCII Value:', 78, '-> Character:', 'N')
('ASCII Value:', 79, '-> Character:', 'O')
('ASCII Value:', 80, '-> Character:', 'P')
('ASCII Value:', 81, '-> Character:', 'Q')
('ASCII Value:', 82, '-> Character:', 'R')
('ASCII Value:', 83, '-> Character:', 'S')
('ASCII Value:', 84, '-> Character:', 'T')
('ASCII Value:', 85, '-> Character:', 'U')
('ASCII Value:', 86, '-> Character:', 'V')
('ASCII Value:', 87, '-> Character:', 'W')
('ASCII Value:', 88, '-> Character:', 'X')
('ASCII Value:', 89, '-> Character:', 'Y')
('ASCII Value:', 90, '-> Character:', 'Z')
('ASCII Value:', 91, '-> Character:', '[')
('ASCII Value:', 92, '-> Character:', '\\')
('ASCII Value:', 93, '-> Character:', ']')
('ASCII Value:', 94, '-> Character:', '^')
('ASCII Value:', 95, '-> Character:', '_')
('ASCII Value:', 96, '-> Character:', '`')
('ASCII Value:', 97, '-> Character:', 'a')
('ASCII Value:', 98, '-> Character:', 'b')
('ASCII Value:', 99, '-> Character:', 'c')
('ASCII Value:', 100, '-> Character:', 'd')
('ASCII Value:', 101, '-> Character:', 'e')
23
('ASCII Value:', 102, '-> Character:', 'f')
('ASCII Value:', 103, '-> Character:', 'g')
('ASCII Value:', 104, '-> Character:', 'h')
('ASCII Value:', 105, '-> Character:', 'i')
('ASCII Value:', 106, '-> Character:', 'j')
('ASCII Value:', 107, '-> Character:', 'k')
('ASCII Value:', 108, '-> Character:', 'l')
('ASCII Value:', 109, '-> Character:', 'm')
('ASCII Value:', 110, '-> Character:', 'n')
('ASCII Value:', 111, '-> Character:', 'o')
('ASCII Value:', 112, '-> Character:', 'p')
('ASCII Value:', 113, '-> Character:', 'q')
('ASCII Value:', 114, '-> Character:', 'r')
('ASCII Value:', 115, '-> Character:', 's')
('ASCII Value:', 116, '-> Character:', 't')
('ASCII Value:', 117, '-> Character:', 'u')
('ASCII Value:', 118, '-> Character:', 'v')
('ASCII Value:', 119, '-> Character:', 'w')
('ASCII Value:', 120, '-> Character:', 'x')
('ASCII Value:', 121, '-> Character:', 'y')
('ASCII Value:', 122, '-> Character:', 'z')
('ASCII Value:', 123, '-> Character:', '{')
('ASCII Value:', 124, '-> Character:', '|')
('ASCII Value:', 125, '-> Character:', '}')
('ASCII Value:', 126, '-> Character:', '~')
('ASCII Value:', 127, '-> Character:', '\x7f')
24
('Character:', 'P', '-> ASCII Value:', 80)
('Character:', 'r', '-> ASCII Value:', 114)
('Character:', 'o', '-> ASCII Value:', 111)
('Character:', 'g', '-> ASCII Value:', 103)
('Character:', 'r', '-> ASCII Value:', 114)
('Character:', 'a', '-> ASCII Value:', 97)
('Character:', 'm', '-> ASCII Value:', 109)
('Character:', 'm', '-> ASCII Value:', 109)
('Character:', 'i', '-> ASCII Value:', 105)
('Character:', 'n', '-> ASCII Value:', 110)
('Character:', 'g', '-> ASCII Value:', 103)
('Character:', '!', '-> ASCII Value:', 33)
RESULT:
Thus the above program has been executed and verified successfully.
25
EX.NO:6 EVALUATE EXPRESSIONS AND CALCULATE ABSOLUTE VALUE
WITHOUT ABS()
Write a Python program to evaluate expressions and calculate the absolute value of a
number without using the abs() function.
Task 1: Evaluate Expressions. Assume that x = 3 and y = 5. Evaluate the following
expressions and print the results:
x == y
x > y - 3
x <= y - 2
x == y or x > 2
x != 6 and y > 10
x > 0 and x < 100
Task 2: Absolute Value Calculation Without Using abs().
Assume x refers to a number.
calculates and prints the absolute value of x without using Python's abs() function
and also evaluates expressions involving x.
26
EVALUATE EXPRESSIONS AND CALCULATE
ABSOLUTE VALUE WITHOUT ABS()
Aim:
To Write a Python program to evaluate expressions and calculate the absolute value of a
number without using the abs() function.
Algorithm:
Step 3: Evaluate the expression x > y - 3. Subtract 3 from y and check if x is greater than the
result.
Step 4: Evaluate the expression x <= y - 2.Subtract 2 from y and check if x is less than or equal
to the result.
than 2.
Step 6: Evaluate the expression x != 6 and y > 10. Check if x is not equal to 6 and if y is
Step 7: Evaluate the expression x > 0 and x < 100. Check if x is greater than 0 and less than
100.
Step 9: If x is less than 0, multiply it by -1 to get the absolute value. Example: If x = -7, then
absolute_value = -x.
Step 10: If x is already greater than or equal to 0, simply use x as the absolute value. Example: If x =
7, then absolute_value = x.
Step 11: Print the absolute value of x and any other relevant expressions.
27
Coding:
28
OUTPUT:
Enter a positive integer: 25
Task 1: Evaluate Expressions
('x == y:', False)
('x > y - 3:', True)
('x <= y - 2:', True)
('x == y or x > 2:', True)
('x != 6 and y > 10:', False)
('x > 0 and x < 100:', True)
RESULT:
Thus the above program has been executed and verified successfully.
29
EX.NO:7 FACTORIAL CALCULATOR USING WHILE LOOP
Write a Python program that computes the factorial of a given integer N using a while loop.
Task: Accept an integer input N from the user.
Initialize a variable result to 1 (since the factorial of 0 is 1).
Use a while loop to multiply result by each integer from 1 to N.
Print the final value of result after the loop ends, which will be the factorial of N.
30
FACTORIAL CALCULATOR USING WHILE LOOP
AIM:
To write a Python program that computes the factorial of a given integer N using a while loop.
ALGORITHM :
Example: result = 1
Step 4: Inside the loop, multiply result by each integer from 1 to NNN.
Example: i += 1
Step 6: After the loop ends, print the final value of result, which will be the factorial of NNN.
31
CODING:
# Accept an integer input N from the user
N = int(input("Enter an integer to compute its factorial: "))
32
OUTPUT:
Enter an integer to compute its factorial: 5
The factorial of 5 is 120.
RESULT:
Thus the above program has been executed and verified successfully.
33
EX.NO:8 TRIANGLE SIDE EQUALITY VALIDATOR
Write a Python program that accepts the lengths of three sides of a triangle and checks if it is an
equilateral triangle (all sides equal).
Task: Determine if a Triangle is Equilateral
Accept the lengths of the three sides of the triangle from the user.
Compare the three sides to check if all the sides are equal.
If all sides are equal, print that the triangle is equilateral.
If the sides are not equal, print that the triangle is not equilateral.
34
TRIANGLE SIDE EQUALITY VALIDATOR
AIM:
To write a program that accepts the lengths of three sides of a triangle and checks if it is an
equilateral triangle (all sides equal).
ALGORITHM:
Step 1: Accept the lengths of the three sides of the triangle from the user.
Step 3: If all sides are equal, print that the triangle is equilateral.
Step 4: If the sides are not equal, print that the triangle is not equilateral.
35
CODING:
# Accepting the lengths of the three sides of the triangle from the user
side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
36
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
37
EX.NO:8 STRING INDEXING AND SUBSTRING EXTRACTION IN PYTHON
Write a Python program that demonstrates how to access characters and substrings in a string.
Task 1: Accessing Characters in a String
Access and print the first character of a string.
Access and print the last character of a string.
Access and print a character at a specific index (e.g., the 3rd character).
Access a character using a negative index (e.g., the 2nd character from the end).
Task 2: Accessing Substrings in a String
Print the first 5 characters of the string.
Print a substring from the 3rd character to the 7th character (not including the 7th
character).
Print a substring from the 5th character to the end of the string.
Print a substring from the beginning of the string to the 4th character (not including the
4th character).
Print a substring from the 2nd to the 5th character of a given string
38
STRING INDEXING AND SUBSTRING EXTRACTION IN PYTHON
AIM:
To write a program that demonstrates how to access characters and substrings in a string.
ALGORITHM:
Step 2: Access and print the first character of the string using index 0.
Step 3: Access and print the last character of the string using index -1.
Step 4: Access and print a character at a specific index (e.g., 3rd character) using positive indexing.
Step 5: Access and print a character using a negative index (e.g., the 2nd character from the end)
Step 7: Print a substring from the 3rd character to the 7th character (not including the 7th character)
using slicing.
Step 8: Print a substring from the 5th character to the end of the string using slicing.
Step 9: Print a substring from the beginning of the string to the 4th character (not including the 4th
Step 10: Print a substring from the 2nd to the 5th character of the string using slicing.
39
CODING:
# Accept a string input from the user
string = input("Enter a string: ")
# Task 1: Accessing Characters in a String
print("\n 1: Accessing Characters in a String")
# Access and print the first character of the string
print("First character:", string[0])
# Access and print the last character of the string
print("Last character:", string[-1])
# Access and print the 3rd character (index 2)
print("3rd character:", string[2])
# Access and print the 2nd character from the end (negative index -2)
print("2nd character from the end:", string[-2])
40
OUTPUT:
Enter a string: PythonProgramming
RESULT:
Thus the above program has been executed and verified successfully.
41
EX.NO:10 PYTHON FILE HANDLING: OPERATIONS FOR READING,
WRITING, AND MANIPULATING DIRECTORIES
42
PYTHON FILE HANDLING: OPERATIONS FOR READING,
WRITING, AND MANIPULATING DIRECTORIES
AIM:
To write a program that demonstrates how to read from a text file and display its contents, write
to a text file by appending or overwriting data and manipulate files and directories by creating, renaming,
and deleting files and directories.
ALGORITHM:
Step 1: Create a text file named sample.txt with some content (e.g., a few lines of text).
Step 2: Open the sample.txt file in read mode ('r').
Step 3: Read the contents of the file using the read() or readlines() method.
Step 4: Display the contents of the file to the screen.
Step 5: Close the file after reading.
Step 1: Open or create a text file named output.txt in write mode ('w').
Step 2: Write a new line of text to output.txt using the write() method.
Step 3: Open the same file in append mode ('a').
Step 4: Append more text to output.txt using the write() method.
Step 5: Close the file after writing.
43
CODING:
import os
44
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
45
EX.NO:11 LIST MANIPULATION OPERATIONS IN PYTHON
Write a Python program that performs the following operations on a list of integers:
(i) Create a list of integers.
(ix) Display the list after each operation to show the changes.
Tasks:
Initialize a list with some integer values.
Add new integers to the list.
Remove integers from the list.
Access and print elements at specific positions using their index.
Change values of elements in the list.
Display the length of the list.
Sort the list in ascending order and display the result.
Reverse the order of elements in the list and display the result.
Print the list after each modification to show the updated state.
46
LIST MANIPULATION OPERATIONS IN PYTHON
AIM:
To write a program to list manipulation operations in python.
ALGORITHM:
Create a list called numbers with integer values like [10, 20, 30, 40, 50].
Use the remove() method to remove the elements 20 and 40 from the list. The remove()
method removes the first occurrence of a given value.
After this operation, print the updated list.
Access an element in the list by specifying its index (e.g., access the element at index 2).
Print the accessed element.
Modify an element in the list by specifying its index. For example, change the element at
index 1 to 100.
After this operation, print the updated list.
Use the len() function to find the length of the list and print it.
Use the sort() method to sort the elements in the list in ascending order.
After sorting, print the updated list.
Use the reverse() method to reverse the order of elements in the list.
After reversing, print the updated list.
47
Throughout the program, display the list after each operation to show the changes made at
each step. Each step modifies the list, and the program prints the list at every modification.
48
CODING:
# Task: Perform various operations on a list of integers
# Initialize a list with some integer values
numbers = [10, 20, 30, 40, 50]
print("Initial list:", numbers)
# (ii) Add elements to the list
numbers.append(60)
numbers.append(70)
print("\nAfter adding elements (60 and 70):", numbers)
# (iii) Remove elements from the list
numbers.remove(20) # Remove the first occurrence of 20
numbers.remove(40) # Remove the first occurrence of 40
print("\nAfter removing elements (20 and 40):", numbers)
# (iv) Access elements by their index
print("\nElement at index 2:", numbers[2]) # Access element at index 2 (should be 50)
# (v) Modify elements in the list
numbers[1] = 100 # Change the element at index 1 to 100
print("\nAfter modifying element at index 1:", numbers)
# (vi) Find and display the length of the list
print("\nLength of the list:", len(numbers))
# (vii) Sort the list in ascending order
numbers.sort()
print("\nList after sorting in ascending order:", numbers)
# (viii) Reverse the list
numbers.reverse()
print("\nList after reversing the order:", numbers)
# (ix) Display the list after each operation (already done throughout the program)
Print(“\n List:”,numbers)
49
OUTPUT:
Initial list: [10, 20, 30, 40, 50]
After adding elements (60 and 70): [10, 20, 30, 40, 50, 60, 70]
After removing elements (20 and 40): [10, 30, 50, 60, 70]
Element at index 2: 50
List after sorting in ascending order: [10, 50, 60, 70, 100]
List after reversing the order: [100, 70, 60, 50, 10]
List:[100,70,60,50,10]
RESULT:
Thus the above program has been executed and verified successfully.
50
EX.NO:12 DICTIONARY MANIPULATION: PERSON INFORMATION MANAGEMENT
51
DICTIONARY MANIPULATION: PERSON INFORMATION MANAGEMENT
AIM :
To write a program to manipulate dictionary operations.
ALGORITHM:
Initialize a dictionary with key-value pairs, where the keys represent attributes (e.g., name,
age, city) and the values are the corresponding information.
Use the dictionary's key and assign it a new value to add a new key-value pair to the
dictionary.
Access the specific key you want to update and assign it a new value to modify the value of
an existing key.
Use the del statement to delete a specific key-value pair from the dictionary.
Access the value of a specific key by referring to the key name and print its value.
Step 6: Loop Through the Dictionary and Print All Key-Value Pairs
Use a loop to iterate through the dictionary and print each key-value pair.
52
CODING:
# Task: Perform various operations on a dictionary
# (i) Create a dictionary that stores information about a person
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
print("Initial dictionary:", person)
# (ii) Add a new key-value pair to the dictionary
person["email"] = "[email protected]"
print("\nAfter adding a new key-value pair (email):", person)
# (iii) Update an existing key-value pair in the dictionary
person["age"] = 31 # Update the age to 31
print("\nAfter updating the 'age' key:", person)
# (iv) Delete a key-value pair from the dictionary
del person["city"] # Remove the key "city"
print("\nAfter deleting the 'city' key:", person)
# (v) Retrieve and print the value of a specific key in the dictionary
print("\nValue of 'name' key:", person["name"])
# (vi) Loop through the dictionary and print all key-value pairs
print("\nLooping through the dictionary:")
for key, value in person.items():
print(f"{key}: {value}")
53
OUTPUT:
Initial dictionary: {'name': 'John Doe', 'age': 30, 'city': 'New York'}
After adding a new key-value pair (email): {'name': 'John Doe', 'age': 30, 'city': 'New York',
'email': '[email protected]'}
After updating the 'age' key: {'name': 'John Doe', 'age': 31, 'city': 'New York', 'email':
'[email protected]'}
After deleting the 'city' key: {'name': 'John Doe', 'age': 31, 'email':
'[email protected]'}
RESULT:
Thus the above program has been executed and verified successfully.
54
EX.NO:13 BANK ACCOUNT MANAGEMENT SYSTEM WITH
ALPHABETICAL LISTING
Write a python program to Update the __str__ method in the Bank class to display accounts in
alphabetical order by account holder name.
Task 1: Implement a __str__ method in SavingsAccount class
Implement or modify the __str__ method in the SavingsAccount class to return a string
representation of the account in a meaningful way (e.g., showing the account holder name,
account balance, etc.).
Task 2: Update the __str__ method in Bank class:
Locate the __str__ method in the Bank class.
Modify the method to return a string of account details sorted by the account holder’s name.
Hint: Use the sorted() function with a lambda function to sort the accounts by the account
holder’s name.
Task 3: Test the changes:
Test the updated __str__ method in the Bank class to ensure that accounts are listed in
alphabetical order by account holder name.
55
BANK ACCOUNT MANAGEMENT SYSTEM WITH ALPHABETICAL LISTING
AIM:
To write a python program to Update the __str__ method in the Bank class to display accounts
ALGORITHM:
Step 1: Define the __str__ method in the SavingsAccount class to return a string with the account
holder's name and balance.
Step 2: In the Bank class, update the __str__ method to sort accounts by the account holder’s name
using sorted() with a lambda function.
Step 3: Return a string representation of all accounts, iterating through the sorted list and calling each
account’s __str__ method.
Step 4: Test the implementation by creating SavingsAccount instances, adding them to a Bank object,
and printing the Bank object to verify alphabetical sorting.
56
CODING:
# Task 1: Implement a __str__ method in the SavingsAccount class
class SavingsAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder
self.balance = balance
def __str__(self):
# Return a string representation of the SavingsAccount
return f"Account Holder: {self.account_holder}, Balance: ${self.balance:.2f}"
57
OUTPUT:
Bank Accounts:
Account Holder: Alice Smith, Balance: $2500.75
Account Holder: Bob Johnson, Balance: $1200.00
Account Holder: John Doe, Balance: $1500.50
RESULT:
Thus the above program has been executed and verified successfully.
58
EX.NO:14 STUDENT DATA SHUFFLE AND SORT PROGRAM
Define a list of student data (e.g., name, age, grade, etc.). Each student item can be represented
as a dictionary or a tuple. Shuffle the student list using Python random. shuffle() method to randomize
the order.
Task 2: Sort the list and Display the sorted list: After shuffling, sort the list by a specific attribute (e.g.,
student name) using the sort() method. Print the sorted list of students to show the data after sorting.
59
STUDENT DATA SHUFFLE AND SORT PROGRAM
AIM:
To write a program to student data shuffle and sort program.
ALGORITHM:
Step 1:Create a list of student data, where each student is represented as a dictionary with attributes like
name, age, and grade.
Step 2:Shuffle the list using Python’s random.shuffle() method to randomize the order of students.
Step 3:Sort the shuffled list by a specific attribute (e.g., name) using the sort() method with a custom
key.
Step 4:Print the shuffled list to show the random order of student data.
Step 5:Print the sorted list to display the student data ordered by the specified attribute.
60
CODING:
import random
# Task 1: Create a list of student dictionaries
students = [
{"name": "Alice", "age": 20, "grade": 88},
{"name": "Bob", "age": 22, "grade": 75},
{"name": "Charlie", "age": 19, "grade": 92},
{"name": "Diana", "age": 21, "grade": 85},
{"name": "Eve", "age": 20, "grade": 90},
]
# Print original list
print "Original list of students:"
for student in students:
print student
# Shuffle the student list
random.shuffle(students)
# Print shuffled list
print "\nShuffled list of students:"
for student in students:
print student
# Task 2: Sort the list by the 'name' attribute
students.sort(key=lambda x: x["name"])
61
OUTPUT:
Original list of students:
{'grade': 88, 'age': 20, 'name': 'Alice'}
{'grade': 75, 'age': 22, 'name': 'Bob'}
{'grade': 92, 'age': 19, 'name': 'Charlie'}
{'grade': 85, 'age': 21, 'name': 'Diana'}
{'grade': 90, 'age': 20, 'name': 'Eve'}
RESULT:
Thus the above program has been executed and verified successfully.
62
EX.NO:15 IMPLEMENTING COMPARISON METHODS IN THE STUDENT CLASS
Write a python program for Add Comparison Methods to the Student Class: How could you adjust the
comparison methods to compare other attributes of the Student class, such as age or grade, rather than
only the name?
63
IMPLEMENTING COMPARISON METHODS IN THE STUDENT CLASS
AIM:
To write a program to implementing comparison methods in the student class.
ALGORITHM:
Step 1: Define the Student class with attributes like name, age, and grade in the __init__
method.
Step 2: Implement the equality method (__eq__) to compare two Student objects based on their
names.
Step 3: Add comparison methods (__lt__, __le__, __gt__, __ge__) to compare Student
objects based on their names using appropriate operators.
Step 4: Test the comparison methods by creating two Student objects and comparing them using the
implemented methods for equality and other comparisons.
64
CODING:
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
return self.grade - other.grade # Positive if self has higher grade, negative if lower, 0 if same
65
# Task 3: Test the comparison methods
student1 = Student("Alice", 20, 85)
student2 = Student("Bob", 22, 90)
student3 = Student("Alice", 19, 92) # Same name as student1 but different age and grade
# Test equality
print "Is student1 equal to student3 (same name)?", student1 == student3
print "Is student1 equal to student2 (different name)?", student1 == student2
66
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
67
EX.NO:16 SORTED LIST CHECKER: VERIFY ASCENDING ORDER
68
SORTED LIST CHECKER: VERIFY ASCENDING ORDER
AIM:
To write a python program for isSorted Checking List Order
ALGORITHM:
Step 2: Check if the list is empty or has only one element. If true, return True, as the list is considered
sorted.
Step 3: If the list has more than one element, start a loop to iterate through the list from the first element
to the second-to-last element.
Step 4: In each iteration, compare the current element with the next element.
Step 5: If any element is greater than its successor, return False, as the list is not sorted.
Step 6: If the loop completes without finding any unsorted pair, return True, indicating the list is sorted
in ascending order.
69
CODING:
def isSorted(lst):
"""Check if the given list is sorted in ascending order."""
# Task 1: If the list is empty or has one element, it's considered sorted
if len(lst) <= 1:
return True
# Task 2: Loop through the list and compare each element with its successor
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]: # If an element is greater than its next one, not sorted
return False
# Test Cases
print "Test Case 1 (Sorted List):", isSorted([1, 2, 3, 4, 5]) # True
print "Test Case 2 (Unsorted List):", isSorted([3, 1, 4, 2]) # False
print "Test Case 3 (Single Element List):", isSorted([10]) # True
print "Test Case 4 (Empty List):", isSorted([]) # True
print "Test Case 5 (Duplicates in Sorted Order):", isSorted([2, 2, 3, 3, 5, 6]) # True
print "Test Case 6 (Descending Order):", isSorted([5, 4, 3, 2, 1]) # False
70
OUTPUT:
Test Case 1 (Sorted List): True
RESULT:
Thus the above program has been executed and verified successfully.
71
EX.NO:17 PYTHON TURTLE GRAPHICS: DRAWING CIRCLES WITH
CUSTOM CENTER AND RADIUS
72
PYTHON TURTLE GRAPHICS: DRAWING CIRCLES WITH CUSTOM
CENTER AND RADIUS
AIM:
To write a python program for draw a Circle with a Turtle.
ALGORIHM:
Step 1:Define a function drawCircle(t, x, y, radius) that accepts the following arguments:
Step 2: Calculate the distance the turtle moves per step using the formula:
step_distance = 2.0 * π * radius / 120.0
Use t.penup() to lift the pen and avoid drawing while moving to the starting point.
Use t.goto(x, y - radius) to position the turtle at the starting point of the circle (adjusting for
the radius).
73
CODING:
import turtle
import math
turtle.done()
74
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
75
EX.NO:18 CUSTOM RGB POSTERIZATION FOR IMAGE PROCESSING
Write a python program for Define and Test the posterize Function
Task 1: Define the posterize function:
Create a function posterize that expects the following arguments:
An image (e.g., a PIL image or another image object).
A tuple of RGB values (for example, (r, g, b)).
The function should modify the image, similar to how a blackAndWhite function works, but
instead of turning pixels black, it will use the provided RGB values.
Task 2:Modify the image and test the function
For each pixel in the image, check the color values (Red, Green, Blue).
If a pixel meets the condition (for example, if the pixel is close enough to a particular color
threshold), change its color to the specified RGB values.
The algorithm should apply the given RGB values as the new color for those pixels that satisfy
the condition.
Test the posterize function with different images and RGB values to ensure the function modifies the
image as expected.
76
CUSTOM RGB POSTERIZATION FOR IMAGE PROCESSING
AIM:
To write a program to custom RGB posterization for image processing
ALGORITHM:
Step 1:Import the necessary libraries (PIL.Image) to load and manipulate the image.
Step 3:Within the posterize function, load the image data using image.load() to get access to
pixel values.
Step 4:Iterate over every pixel in the image using its width and height:
For example, if the average of the pixel's RGB values is less than a threshold (128), change its
color to the target color.
Open an image, apply the posterize function with a target color, display the image, and save
the result.
77
CODING:
Args:
image: A PIL Image object.
target_color: A tuple of RGB values (e.g., (r, g, b)).
"""
# Load the image data
image = image.convert("RGB")
pixels = image.load()
width, height = image.size
for x in range(width):
for y in range(height):
# Get the current pixel's RGB values
r, g, b = pixels[x, y]
78
OUTPUT:
79
After :
RESULT:
Thus the above program has been executed and verified successfully.
80
EX.NO:19 INTERACTIVE LABEL TOGGLE WITH TKINTER
Develop a Python Program to Toggle Label Text Between Hello and Goodbye;
Task 1:Create the user interface:
Use a GUI library like Tkinter (for Python) to create a window.
Add a label widget that will display text
Add a button widget that will allow the user to change the label text when pressed.
Task 2:Define a function to toggle text:
Create a function that changes the text of the label each time the button is pressed.
The function should check the current text of the label. If change it to and vice versa.
Task 3 :Connect the button to the function Test the program:
Set up the button so that when clicked, it calls the function that toggles the label text.
Run the program and test that pressing the button correctly alternates the label text between
Hello and Goodbye
81
INTERACTIVE LABEL TOGGLE WITH TKINTER
AIM:
To write a program to interactive label toggle with tkinter.
ALGORITHM:
Create a function (toggle_text()) to handle the logic of changing the label's text.
Inside the function:
o Check if the current text of the label is "Hello".
o If it is "Hello", change it to "Goodbye".
o Otherwise, change the label's text to "Hello".
Link the button widget to the toggle_text() function so that it is called when the button is
pressed.
Call the root.mainloop() function to run the Tkinter event loop, which keeps the window open
and listens for user interactions.
82
CODING
import tkinter as tk
83
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
84
EX.NO:20 3X3 GRID OF BUTTONS WITH NUMBER LABELS
Develop a python program to create a 3x3 Grid of Buttons with Number Labels
Task 1:Create the user interface:
Use a GUI library like Tkinter (for Python) to create a window.
Set up a Frame or use a layout manager (like grid) to organize the buttons into a 3x3 grid.
Task 2: Create and place the buttons:
Use a loop to create 9 buttons.
Label each button with a number, starting from 1 and increasing across each row.
Place the buttons into the grid using the grid() method or equivalent layout mechanism. The loop
should assign each button to the correct row and column.
Task 3: Test the program:
Run the program and check that 9 buttons are displayed in a 3x3 grid, each labeled correctly
from 1 to 9.
85
3X3 GRID OF BUTTONS WITH NUMBER LABELS
AIM:
To write a program 3x3 grid of buttons with number labels.
ALGORITHM:
Set the font and size for the button text using font=("Arial", 16).
Adjust the size of the buttons by setting the width and height attributes (width=5, height=2).
Add some padding (padx=5, pady=5) between buttons for better layout.
Call root.mainloop() to keep the application running and display the window.
86
CODING:
import tkinter as tk
87
OUTPUT:
RESULT:
Thus the above program has been executed and verified successfully.
88