0% found this document useful (0 votes)
6 views

Python Record 2025

The document outlines multiple Python programming exercises aimed at calculating areas of shapes, exploring strings and variables, demonstrating data types and expressions, calculating minutes in a year, and displaying ASCII values. Each exercise includes a clear aim, algorithm, coding examples, and expected outputs. The programs are designed to help users understand basic programming concepts and operations in Python.

Uploaded by

senthur665
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)
6 views

Python Record 2025

The document outlines multiple Python programming exercises aimed at calculating areas of shapes, exploring strings and variables, demonstrating data types and expressions, calculating minutes in a year, and displaying ASCII values. Each exercise includes a clear aim, algorithm, coding examples, and expected outputs. The programs are designed to help users understand basic programming concepts and operations in Python.

Uploaded by

senthur665
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
You are on page 1/ 88

EX.

NO: 1 TO CALCULATE AREA OF SHAPES

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

base = float(input("Enter the base of the triangle: "))


# Ask the user to input the height of the triangle

height = float(input("Enter the height of the triangle: "))


# Calculate the area of the triangle using the formula: 0.5 * base * height

triangle_area = 0.5 * base * height


# Output the area of the triangle with a descriptive label

print("The area of the triangle is:”,triangle_area)

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:

Task 1: Working with Strings

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.

Task 2: Assignments in Python

Step 5: Assign values to variables representing your age and height.

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.

Task 3: Using Comments

Step 8: Add a comment at the beginning of the program to explain its purpose.

Step 9: Assign values to two numbers.

Step 10: Calculate the sum of the two numbers.

Step 11: Print the result of the sum.

6
# Task 1: Working with Strings
# Creating a string variable to store my full name
full_name = "John Doe"

# Printing the string to display the full name


print("Full Name:", full_name)

# 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)

# Task 2: Assignments in Python


# Assigning values to variables representing age and height
age = 25 # Age in years
height = 5.9 # Height in feet

# Assigning the value of height to another variable


height_in_meters = height * 0.3048 # Converting height from feet to meters
print("Height in Meters:", height_in_meters)

# Modifying the value of the age variable


age = 26 # Updating age
print("Updated Age:", age)

# Task 3: Using Comments


# This program calculates the sum of two numbers

# Assigning values to two numbers


num1 = 10 # First number
num2 = 20 # Second number

7
# Calculating the sum of the two numbers
sum_result = num1 + num2

# Printing the result of the sum


print("Sum of Two Numbers:", sum_result)

8
OUTPUT:

Full Name: John Doe


First 3 Characters: Joh
Full Name with Nickname: John Doe - Johnny
Height in Meters: 1.79832
Updated Age: 26
Sum of Two Numbers: 30

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

Step 1: Create and print a string variable.


Step 2: Create two integer variables, perform an arithmetic operation, and print the result.
Step 3: Create a float variable, perform a mathematical operation, and print the result.
Step 4: Create and print a boolean variable.
Step 5: Create a list variable, add items to it, and print the list.

Task 2: Character Sets

Step 6: Display the ASCII value of a character using ord().


Step 7: Convert an ASCII value back to a character using chr().

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:

# Task 1: Working with Different Data Types


# Creating a string variable and printing it
name = "Alice"
print("String:", name)

# 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)

# Creating a boolean variable and printing it


is_student = False
print("Boolean value:", is_student)

# Creating a list variable, adding items to it, and printing it


fruits = ["Apple", "Banana"]
fruits.append("Cherry") # Adding a new fruit to the list
print("List:", fruits)

# Task 2: Character Sets


# Displaying the ASCII value of a character
char = 'A'
ascii_value = ord(char)
print("ASCII value of", char, "is:", ascii_value)

# Converting an ASCII value back to its character


ascii_to_char = chr(66) # ASCII value for 'B'
print("Character for ASCII value 66 is:", ascii_to_char)

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)

# Using comparison operators to compare two values


is_greater = num1 > num2
print("Comparison (num1 > num2):", is_greater)

# Using logical operators to create boolean expressions


logical_result = is_greater and (num2 < 20)
print("Logical expression result:", logical_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 1: Assume that the year has 365 days.

Step 2: Define the number of hours in a day.

Step 3: Define the number of minutes in an hour.

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.

Step 5: Print the total number of minutes in a year.

15
CODING:

# Calculate the number of minutes in a year


# Assuming a year has 365 days
days_in_year = 365
hours_in_day = 24
minutes_in_hour = 60

# Calculating total minutes in a year


total_minutes = days_in_year * hours_in_day * minutes_in_hour
print("Total minutes in a year:", total_minutes)

16
OUTPUT:

('Total minutes in a year:', 525600)

RESULT:
Thus the above program has been executed and verified successfully.

17
EX. NO: 5 DISPLAY ASCII VALUES AND CHARACTERS

Write a Python program that performs the following tasks:


(i) Prints the first 128 ASCII values and their corresponding characters.
(ii).For a givenstring, prints each character along with its corresponding ASCII value.
Task 1:Print the First 128 ASCII Values and Corresponding Characters:
o Use a loop to iterate through the first 128 ASCII values (0 to 127).
o For each value, print both the ASCII value and the corresponding character.
Task 2: Print Each Character of a Given String Along with Its ASCII Value:
o Assume the variable testString refers to a string.
o Use a loop to print each character of the string, followed by its ASCII value.
o Use the ord() function to get the ASCII value of each character.

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).

Example: for i in range(128):

Step 2: For each value in the loop, print the ASCII value and the corresponding character using chr().

Example: print(i, chr(i))

Task 2: Print Each Character of a Given String Along with Its ASCII Value

Step 3: Define the variable testString to refer to a string.

Example: testString = "Hello"

Step 4: Use a loop to iterate through each character in the string.

Example: for char in testString:

Step 5: For each character, print the character and its corresponding ASCII value using the ord().

Example: print(char, ord(char))

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:

First 128 ASCII Values and Their Corresponding Characters:


('ASCII Value:', 0, '-> Character:', '\x00')
('ASCII Value:', 1, '-> Character:', '\x01')
('ASCII Value:', 2, '-> Character:', '\x02')
('ASCII Value:', 3, '-> Character:', '\x03')
('ASCII Value:', 4, '-> Character:', '\x04')
('ASCII Value:', 5, '-> Character:', '\x05')
('ASCII Value:', 6, '-> Character:', '\x06')
('ASCII Value:', 7, '-> Character:', '\x07')
('ASCII Value:', 8, '-> Character:', '\x08')
('ASCII Value:', 9, '-> Character:', '\t')
('ASCII Value:', 10, '-> Character:', '\n')
('ASCII Value:', 11, '-> Character:', '\x0b')
('ASCII Value:', 12, '-> Character:', '\x0c')
('ASCII Value:', 13, '-> Character:', '\r')
('ASCII Value:', 14, '-> Character:', '\x0e')
('ASCII Value:', 15, '-> Character:', '\x0f')
('ASCII Value:', 16, '-> Character:', '\x10')
('ASCII Value:', 17, '-> Character:', '\x11')
('ASCII Value:', 18, '-> Character:', '\x12')
('ASCII Value:', 19, '-> Character:', '\x13')
('ASCII Value:', 20, '-> Character:', '\x14')
('ASCII Value:', 21, '-> Character:', '\x15')
('ASCII Value:', 22, '-> Character:', '\x16')
('ASCII Value:', 23, '-> Character:', '\x17')
('ASCII Value:', 24, '-> Character:', '\x18')
('ASCII Value:', 25, '-> Character:', '\x19')
('ASCII Value:', 26, '-> Character:', '\x1a')
('ASCII Value:', 27, '-> Character:', '\x1b')
('ASCII Value:', 28, '-> Character:', '\x1c')
('ASCII Value:', 29, '-> Character:', '\x1d')
('ASCII Value:', 30, '-> Character:', '\x1e')
('ASCII Value:', 31, '-> Character:', '\x1f')

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')

('Characters and ASCII Values for the string:', 'Python Programming!')


('Character:', 'P', '-> ASCII Value:', 80)
('Character:', 'y', '-> ASCII Value:', 121)
('Character:', 't', '-> ASCII Value:', 116)
('Character:', 'h', '-> ASCII Value:', 104)
('Character:', 'o', '-> ASCII Value:', 111)
('Character:', 'n', '-> ASCII Value:', 110)
('Character:', ' ', '-> ASCII Value:', 32)

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 &gt; y - 3
x &lt;= y - 2
x == y or x &gt; 2
x != 6 and y &gt; 10
x &gt; 0 and x &lt; 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&#39;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:

Task 1: Evaluate Expressions

Step 1: Assume that x = 3 and y = 5.

Step 2: Evaluate the expression x == y. Compare if x is equal to y.

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.

Step 5: Evaluate the expression x == y or x > 2. Check if either x is equal to y, or if x is greater

than 2.

Step 6: Evaluate the expression x != 6 and y > 10. Check if x is not equal to 6 and if y is

greater than 10.

Step 7: Evaluate the expression x > 0 and x < 100. Check if x is greater than 0 and less than

100.

Task 2: Absolute Value Calculation Without Using abs()

Step 8: Assume that x refers to a number. Example: x = -7.

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:

# Task 1: Evaluate Expressions


x=3
y=5
print("Evaluate Expressions")
# Check if x equals y
print("x == y:", x == y)
# Check if x is greater than y - 3
print("x > y - 3:", x > y - 3)
# Check if x is less than or equal to y - 2
print("x <= y - 2:", x <= y - 2)
# Logical OR: Check if x equals y or x is greater than 2
print("x == y or x > 2:", x == y or x > 2)
# Logical AND: Check if x is not 6 and y is greater than 10
print("x != 6 and y > 10:", x != 6 and y > 10)
# Logical AND: Check if x is between 0 and 100
print("x > 0 and x < 100:", x > 0 and x < 100)
# Adding a line break for better readability
print("\n")

# Task 2: Absolute Value Calculation Without Using abs()


# Assume x refers to a number
x = -7
# Calculate the absolute value of x without using abs()
if x >= 0:
# If x is non-negative, the absolute value is x itself
absolute_value = x
else:
# If x is negative, the absolute value is -x
absolute_value = -x
print("Task 2: Absolute Value Calculation")
print("The absolute value of {x} is:",absolute_value)

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 :

Step 1: Accept an integer input NNN from the user.

 Example: N = int(input("Enter an integer: "))

Step 2: Initialize a variable result to 1 (since the factorial of 0 is 1).

 Example: result = 1

Step 3: Use a while loop to iterate from 1 to NNN.

 Example: while i <= N:

Step 4: Inside the loop, multiply result by each integer from 1 to NNN.

 Example: result = result * i

Step 5: Increment the value of i to proceed to the next number.

 Example: i += 1

Step 6: After the loop ends, print the final value of result, which will be the factorial of NNN.

 Example: print("Factorial of", N, "is:", result)

31
CODING:
# Accept an integer input N from the user
N = int(input("Enter an integer to compute its factorial: "))

# Initialize result to 1 (since the factorial of 0 is 1)


result = 1

# Use a while loop to multiply result by each integer from 1 to N


i=1
while i <= N:
result *= i
i += 1

# Print the final value of result, which is the factorial of N


print(f"The factorial of {N} is {result}.")

32
OUTPUT:
Enter an integer to compute its factorial: 5
The factorial of 5 is 120.

Enter an integer to compute its factorial: 0


The factorial of 0 is 1.

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 2: Compare if all three sides are equal.

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.

Step 5: End the program after displaying the result.

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: "))

# Checking if all sides are equal


if side1 == side2 == side3:
print("The triangle is equilateral.")
else:
print("The triangle is not equilateral.")

36
OUTPUT:

#Sample 1: Equilateral Triangle


Enter the length of the first side: 5
Enter the length of the second side: 5
Enter the length of the third side: 5
The triangle is equilateral.

#Sample 2: Not an Equilateral Triangle


Enter the length of the first side: 3
Enter the length of the second side: 4
Enter the length of the third side: 5
The triangle is not equilateral.

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 1: Accept a string input from the user.

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)

using negative indexing.

Step 6: Print the first 5 characters of the string using slicing.

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

character) using slicing.

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])

# Task 2: Accessing Substrings in a String


print("\n 2: Accessing Substrings in a String")
# Print the first 5 characters of the string
print("First 5 characters:", string[:5])
# Print a substring from the 3rd character to the 7th character (not including the 7th
character)
print("Substring from 3rd to 7th character:", string[2:6])
# Print a substring from the 5th character to the end of the string
print("Substring from 5th character to end:", string[4:])
# Print a substring from the beginning of the string to the 4th character (not including the
4th character)
print("Substring from beginning to 4th character:", string[:3])
# Print a substring from the 2nd to the 5th character
print("Substring from 2nd to 5th character:", string[1:5])

40
OUTPUT:
Enter a string: PythonProgramming

1: Accessing Characters in a String


First character: P
Last character: g
3rd character: t
2nd character from the end: n

2: Accessing Substrings in a String


First 5 characters: Pytho
Substring from 3rd to 7th character: thonP
Substring from 5th character to end: onProgramming
Substring from beginning to 4th character: Pyt
Substring from 2nd to 5th character: ytho

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

Write a Python program that demonstrates how to:


(i)Read from a text file and display its contents.
(ii)Write to a text file by appending or overwriting data.
(iii)Manipulate files and directories by creating, renaming, and deleting files and directories.

Task 1: Reading from a Text File


Create a text file named sample.txt with some content (for example, a few lines of text).
Opens the file sample.txt in read mode (&#39;r&#39;) and prints its contents to the screen.

Task 2: Writing to a Text File


Create or open a text file named output.txt.
Write a new line of text to output.txt using the write() method.
Append more text to the same file using the append mode (&#39;a&#39;), ensuring the new
content is added after the existing content.

Task 3: Manipulating Files and Directories


Create a new directory named my_folder using Python’s os module.
Create a new text file inside my_folder and write some content to it.
Rename the file you just created.
Delete the text file and the directory my_folder.

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:

Task 1: Reading from a Text File

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.

Task 2: Writing to a Text File

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.

Task 3: Manipulating Files and Directories

Step 1: Import the os module to work with files and directories.


Step 2: Create a new directory named my_folder using os.mkdir().
Step 3: Create a new text file inside my_folder using open() and write some content to it.
Step 4: Rename the file you just created using os.rename().
Step 5: Delete the text file using os.remove().
Step 6: Delete the directory my_folder using os.rmdir().

43
CODING:
import os

# Task 1: Reading from a Text File


# Create a sample text file and write some content to it
with open('sample.txt', 'w') as file:
file.write("This is the first line.\n")
file.write("This is the second line.\n")
file.write("This is the third line.\n")
# Open the file in read mode and display its contents
print("Task 1: Reading from a Text File")
with open('sample.txt', 'r') as file:
contents = file.read()
print(contents)

# Task 2: Writing to a Text File


print("\nTask 2: Writing to a Text File")
# Create or open output.txt and write new content to it
with open('output.txt', 'w') as file:
file.write("This is the first line of output.txt.\n")
# Append more text to the same file
with open('output.txt', 'a') as file:
file.write("This is an appended line to output.txt.\n")
# Verify that the content has been written and appended
with open('output.txt', 'r') as file:
print("Content of output.txt:")
print(file.read())

# Task 3: Manipulating Files and Directories


print("\nTask 3: Manipulating Files and Directories")
# Create a new directory named 'my_folder'
os.makedirs('my_folder', exist_ok=True)
# Create a new text file inside 'my_folder' and write content to it
with open('my_folder/my_file.txt', 'w') as file:
file.write("This is a file inside my_folder.\n")
# Rename the file
os.rename('my_folder/my_file.txt', 'my_folder/renamed_file.txt')
# Delete the renamed file
os.remove('my_folder/renamed_file.txt')
# Delete the directory 'my_folder'
os.rmdir('my_folder')
print("\nAll tasks have been completed successfully.")

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.

(ii) Add elements to the list.

(iii) Remove elements from the list.

(iv) Access elements by their index.

(v) Modify elements in the list.

(vi) Find and display the length of the list.

(vii) Sort the list in ascending order.

(viii) Reverse the list.

(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:

Step 1: Initialize a List with Some Integer Values

 Create a list called numbers with integer values like [10, 20, 30, 40, 50].

Step 2: Add Elements to the List

 Use the append() method to add integers 60 and 70 to the list.


 After this operation, print the updated list.

Step 3: Remove Elements from the List

 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.

Step 4: Access Elements by Their Index

 Access an element in the list by specifying its index (e.g., access the element at index 2).
 Print the accessed element.

Step 5: Modify Elements in the List

 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.

Step 6: Find and Display the Length of the List

 Use the len() function to find the length of the list and print it.

Step 7: Sort the List in Ascending Order

 Use the sort() method to sort the elements in the list in ascending order.
 After sorting, print the updated list.

Step 8: Reverse the List

 Use the reverse() method to reverse the order of elements in the list.
 After reversing, print the updated list.

Step 9: Display the List After Each Operation

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

After modifying element at index 1: [10, 100, 50, 60, 70]

Length of the list: 5

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

Write a Python program that performs the following operations on a dictionaries.


(i)Create a dictionary that stores information about a person (e.g., name, age, and city)
.(ii)Add a new key-value pair to the dictionary.
(iii)Update an existing key-value pair.
(iv)Delete a key-value pair from the dictionary.
(v)Retrieve and print the value of a specific key.
(vi)Loop through the dictionary and print all key-value pairs.
Task:
Create a dictionary that stores information about a person (e.g., name, age, and city).
Add a new key-value pair to the dictionary.
Update an existing key-value pair in the dictionary.
Delete a key-value pair from the dictionary.
Retrieve and print the value of a specific key in the dictionary.
Loop through the dictionary and print all key-value pairs.

51
DICTIONARY MANIPULATION: PERSON INFORMATION MANAGEMENT

AIM :
To write a program to manipulate dictionary operations.

ALGORITHM:

Step 1: Create a Dictionary to Store Information

 Initialize a dictionary with key-value pairs, where the keys represent attributes (e.g., name,
age, city) and the values are the corresponding information.

Step 2: Add a New Key-Value Pair

 Use the dictionary's key and assign it a new value to add a new key-value pair to the
dictionary.

Step 3: Update an Existing Key-Value Pair

 Access the specific key you want to update and assign it a new value to modify the value of
an existing key.

Step 4: Delete a Key-Value Pair

 Use the del statement to delete a specific key-value pair from the dictionary.

Step 5: Retrieve and Print the Value of a Specific Key

 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]'}

Value of 'name' key: John Doe

Looping through the dictionary:


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}"

# Task 2: Update the __str__ method in the Bank class


class Bank:
def __init__(self):
self.accounts = []
def add_account(self, account):
self.accounts.append(account)
def __str__(self):
# Sort the accounts by account holder's name in alphabetical order
sorted_accounts = sorted(self.accounts, key=lambda x: x.account_holder)
# Create a string representation of all accounts, sorted alphabetically
account_details = "\n".join(str(account) for account in sorted_accounts)
return f"Bank Accounts:\n{account_details}"

# Task 3: Test the changes


# Creating SavingsAccount instances
account1 = SavingsAccount("John Doe", 1500.50)
account2 = SavingsAccount("Alice Smith", 2500.75)
account3 = SavingsAccount("Bob Johnson", 1200.00)
# Creating a Bank instance and adding accounts to it
bank = Bank()
bank.add_account(account1)
bank.add_account(account2)
bank.add_account(account3)
# Testing the __str__ method of the Bank class
print(bank)

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"])

# Print sorted list


print "\nSorted list of students by name:"
for student in students:
print student

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'}

Shuffled list of students:


{'grade': 85, 'age': 21, 'name': 'Diana'}
{'grade': 75, 'age': 22, 'name': 'Bob'}
{'grade': 90, 'age': 20, 'name': 'Eve'}
{'grade': 92, 'age': 19, 'name': 'Charlie'}
{'grade': 88, 'age': 20, 'name': 'Alice'}

Sorted list of students by name:


{'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?

Task 1:Implement an equality method:


Add a method to the Student class to compare if two Student objects are equal. This method should
compare the students names and return True if the names are the same, or False if they are different.
Task 2:Implement comparison methods for other possible comparisons:
Add methods to compare the Student objects based on their names. These methods should support
comparisons like less than (&lt;), greater than (&gt;), less than or equal to (&lt;=), and greater than or
equal to (&gt;=).
Use the appropriate comparison operators on the students&#39; names in these methods.
Task 3: Test the comparison methods:
Create two Student objects and test the comparison methods to ensure they work correctly by
comparing their names.

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

# Task 1: Equality comparison (==)


def __eq__(self, other):
if isinstance(other, Student):
return self.name == other.name
return False

# Task 2: Comparison by name (<, >, <=, >=)


def __lt__(self, other):
return self.name < other.name # Compare names alphabetically

def __gt__(self, other):


return self.name > other.name

def __le__(self, other):


return self.name <= other.name

def __ge__(self, other):


return self.name >= other.name

# Optional: Comparison by age


def compare_by_age(self, other):
return self.age - other.age # Returns positive if self is older, negative if younger, 0 if
same age

# Optional: Comparison by grade


def compare_by_grade(self, other):

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

# Test name comparisons


print "Is student1 < student2 (name)?", student1 < student2
print "Is student2 > student1 (name)?", student2 > student1
print "Is student1 <= student3 (name)?", student1 <= student3
print "Is student2 >= student3 (name)?", student2 >= student3

# Test age and grade comparisons


print "Comparing ages (positive means student1 is older):",
student1.compare_by_age(student2)
print "Comparing grades (positive means student1 has a higher grade):",
student1.compare_by_grade(student2)

66
OUTPUT:

Is student1 equal to student3 (same name)? True


Is student1 equal to student2 (different name)? False
Is student1 < student2 (name)? True
Is student2 > student1 (name)? True
Is student1 <= student3 (name)? True
Is student2 >= student3 (name)? True
Comparing ages (positive means student1 is older): -2
Comparing grades (positive means student1 has a higher grade): -5

RESULT:

Thus the above program has been executed and verified successfully.

67
EX.NO:16 SORTED LIST CHECKER: VERIFY ASCENDING ORDER

Write a python program for isSorted Checking List Order?


Task 1:Define the isSorted function:
Implement a function called isSorted that takes a list as an argument.
If the list is empty or has only one element, return True (since a list with one or no elements is
considered sorted).
Task 2: Loop through the list for larger lists:
For lists with two or more elements, loop through the list and compare each item (except the last
one) with its successor.
If any item is greater than its successor, return False (since the list is not sorted).
Task 3: Return True if the list is sorted:
If no item is found that is greater than its successor, return True, indicating the list is sorted in
ascending order.

68
SORTED LIST CHECKER: VERIFY ASCENDING ORDER

AIM:
To write a python program for isSorted Checking List Order

ALGORITHM:

Step 1: Define the function isSorted(lst) to accept a list as an argument.

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

# Task 3: If no unsorted pair is found, return True


return True

# 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

Test Case 2 (Unsorted List): False

Test Case 3 (Single Element List): True

Test Case 4 (Empty List): True

Test Case 5 (Duplicates in Sorted Order): True

Test Case 6 (Descending Order): False

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

Write a python program for draw a Circle with a Turtle


Task 1:Create a function drawCircle that expects the following arguments:
A Turtle object to draw the circle.
The coordinates of the circle’s center point (x, y).
The radius of the circle.
Task 2: Calculate the distance moved per step:
Use the formula 2.0 * π * radius / 120.0 to calculate the distance the Turtle will move each time.
Task 3: Draw the circle and test the function
Move the Turtle to the specified center point of the circle (using turtle.penup() and turtle.goto(x,y)).
Set the turtle to draw (using turtle.pendown()).
Use a loop to draw the circle by turning 3 degrees and moving the calculated distance 120 times.
For each iteration, move the turtle forward by the calculated distance and turn it 3 degrees.
Test the drawCircle function with different center points and radii to ensure it draws the expected circle.

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:

 t: the turtle object used for drawing.


 x, y: coordinates for the center of the circle.
 radius: the radius of the circle.

Step 2: Calculate the distance the turtle moves per step using the formula:
step_distance = 2.0 * π * radius / 120.0

Step 3: Move the turtle to the center position for drawing:

 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).

Step 4: Set the pen down using t.pendown() to begin drawing.

Step 5: Use a loop to draw the circle:

 Move the turtle forward by step_distance for each iteration.


 Turn the turtle 3 degrees to create the curve of the circle (this is repeated 120 times to
complete a full circle).

73
CODING:
import turtle
import math

def drawCircle(t, x, y, radius):


# Move turtle to starting position
t.penup()
t.goto(x, y - radius) # Move to the bottom of the circle
t.pendown()

# Calculate step distance


step_distance = (2.0 * math.pi * radius) / 120.0

# Draw the circle


for _ in range(120):
t.forward(step_distance)
t.left(3) # Turn 3 degrees

# Create turtle object


t = turtle.Turtle()
t.speed(0) # Set to fastest speed

# Test the function with different circles


drawCircle(t, 0, 0, 50)
drawCircle(t, -100, 100, 75)
drawCircle(t, 100, -100, 100)

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 2:Define the posterize function:

 Accept an image object and a target RGB color as input.


 The function will modify pixels of the image that satisfy a certain condition (e.g., dark pixels).

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 each pixel, get the current RGB values.

Step 5:Apply the condition to decide which pixels will be changed:

 For example, if the average of the pixel's RGB values is less than a threshold (128), change its
color to the target color.

Step 6:Test the posterize function:

 Open an image, apply the posterize function with a target color, display the image, and save
the result.

77
CODING:

from PIL import Image

def posterize(image, target_color):


"""
Modify the image to change certain pixels to the given RGB color.

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]

# Condition to posterize the pixel (example: if average of RGB < 128)


if (r + g + b) // 3 < 128:
pixels[x, y] = target_color

# Task 2: Test the posterize function


if __name__ == "__main__":
# Open an image
image = Image.open("example.jpg")

# Define the target color


target_color = (255, 0, 0) # Bright red

# Apply the posterize function


posterize(image, target_color)

# Show and save the modified image


image.show()
image.save("posterized_image.png")

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:

Step 1: Create the User Interface (UI)

 Import the Tkinter library to work with GUI components.


 Create the main window for the application.
 Add a label widget to display text. Initially set the label text to "Hello".
 Add a button widget that will trigger the toggle action when pressed.

Step 2: Define the Function to Toggle Text

 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".

Step 3: Connect the Button to the Function

 Link the button widget to the toggle_text() function so that it is called when the button is
pressed.

Step 4: Run the Application

 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

# Task 1: Create the user interface


def toggle_text():
"""Toggle the label's text between 'Hello' and 'Goodbye'."""
if label.cget("text") == "Hello":
label.config(text="Goodbye")
else:
label.config(text="Hello")

# Create the main window


root = tk.Tk()
root.title("Toggle Text")

# Create a label widget


label = tk.Label(root, text="Hello", font=("Arial", 24))
label.pack(pady=20)

# Create a button widget


button = tk.Button(root, text="Toggle", command=toggle_text, font=("Arial", 16))
button.pack(pady=20)

# Task 3: Run the application


root.mainloop()

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:

Step 1: Initialize the main window

 Create a main window using the Tkinter library.


 Set the window title to "3x3 Grid of Buttons."

Step 2: Create the button grid

 Loop through rows and columns to create the buttons.


o The outer loop (for i in range(3)) iterates over the rows.
o The inner loop (for j in range(3)) iterates over the columns.
 For each button:
o Calculate the button number (button_number = i * 3 + j + 1).
o Create the button widget with the calculated number as the text.
o Place the button in the correct position using the grid() method with the row and
column arguments.

Step 3: Customize the button appearance

 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.

Step 4: Run the main loop

 Call root.mainloop() to keep the application running and display the window.

86
CODING:
import tkinter as tk

# Task 1: Create the user interface


# Create the main window
root = tk.Tk()
root.title("3x3 Grid of Buttons")

# Create a 3x3 grid of buttons


for i in range(3):
for j in range(3):
button_number = i * 3 + j + 1
button = tk.Button(root, text=str(button_number), font=("Arial", 16), width=5,
height=2)
button.grid(row=i, column=j, padx=5, pady=5)

# Task 3: Run the application


root.mainloop()

87
OUTPUT:

RESULT:

Thus the above program has been executed and verified successfully.

88

You might also like