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

Final Python Project File

This document is a practical file for the course 'Python Programming for Artificial Intelligence' at Chitkara University, submitted by Nikhil Tanwar. It includes various Python programming exercises covering topics such as area calculation, number checking, string manipulation, and matrix operations. The file serves as a partial fulfillment for the Bachelor of Engineering degree in Computer Science & Engineering (AI).

Uploaded by

nikhiltanwar6714
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Final Python Project File

This document is a practical file for the course 'Python Programming for Artificial Intelligence' at Chitkara University, submitted by Nikhil Tanwar. It includes various Python programming exercises covering topics such as area calculation, number checking, string manipulation, and matrix operations. The file serves as a partial fulfillment for the Bachelor of Engineering degree in Computer Science & Engineering (AI).

Uploaded by

nikhiltanwar6714
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Python Programming for Artificial Intelligence (24CAI1101)

Practical File of
Python Programming
Using Artificial Intelligence
24CAI1101
Submitted

in partial fulfillment for the award of the degree of

BACHELEOR OF ENGINEERING
in

BE-COMPUTER SCIENCE & ENGINEERING (AI)

CHITKARA UNIVERSITY

CHANDIGARH-PATIALA NATIONAL HIGHWAY


RAJPURA (PATIALA) PUNJAB-140401 (INDIA)

December, 2024

Submitted To: Submitted By:

Faculty name: Dr. Monika Sethi Name: Nikhil Tanwar


Designation: Roll No.: 2410992619
Chitkara University, Punjab Sem, Batch :1st semester;
G-25
INDEX

0|Page
Python Programming for Artificial Intelligence (24CAI1101)

Sr. Practical Name Page Teacher Sign


No. No.
1.a Program to Calculate the Area of a Triangle

1.b Program to Swap Two Variables 4

1.c Write a program to convert Celsius to Fahrenheit 4

2.a Python Program to Check if a Number is Odd or Even

2.b Python Program to Check if a Number is Positive, Negative or 0 5

Python Program to Check Armstrong Number 6


2.c
7

3.a Python program to check if a given number is Fibonacci number


8
3.b Python program to print cube sum of first n natural numbers
9
3.c Python program to print all odd numbers in a range
10

4.a Python Program to Print Pascal Triangle 11

4.b Printing following Pattern for n number:


11111 12
2222
333
44
5

5 Program converting character of each word capitalized 13

6.a Program to reverse a list 14

6.b Program to print the largest number of a list 15

1|Page
Python Programming for Artificial Intelligence (24CAI1101)

7 program to print the sum of each row of m*n matrix 16

8.a program that reads a string from keyboard and display: 17


* The number of uppercase letters in the string.
* The number of lowercase letters in the string.
* The number of digits in the string.
* The number of whitespace characters in the string

8.b Python Program to Find Common Characters in Two Strings 19


8.c
Python Program to Count the Number of Vowels in a String
20

9.a program to check if a specified element presents in a tuple of 21


tuples.
9.b
program to remove an empty tuple(s) from a list of tuples 22

10 Program in Python to Find the Differences Between Two Lists Using Sets. 23

11.a
Python program Remove duplicate values across Dictionary Values 24
11.b
Python program to Count the frequencies in a list using dictionary in 25
Python.

12.a Python Program to Capitalize First Letter of Each Word in a File 26


Python Program to Print the Contents of File in Reverse Order.
12.b 27

13 WAP to catch an exception and handle it using try and except code blocks
28

2|Page
Python Programming for Artificial Intelligence (24CAI1101)

14 Program to Append, Delete and Display Elements of a List using Classes.


30

32
15 Python Program to Find the Area and Perimeter of the Circle using Class.

16 Python programme to create an interactive application(calculator) 33

3|Page
Python Programming for Artificial Intelligence (24CAI1101)

Program 1.a: ……………Area Of Triangle…..………..


Objective: Write a Python Program to Calculate the Area of a Triangle Solution:
a=float(input("First side of triangle")) #takes input for first side b=float(input("Second
side of triangle")) #takes input for second side c=float(input("Third side of triangle"))
#takes input for third side
s=(a+b+c)/2 #takes sum of sides and divides it by 2
Area=(s*(s-a)*(s-b)*(s-c))**0.5 # Area of triangle print("Area
of triangle is",Area)

Output:
First side of triangle 7
Second side of triangle 5
Third side of triangle 6
Area of triangle is 14.696938456699069
Result:

Program 1.b: ……………Swap Two Variables…..………..


Objective: Write a Python Program to Swap Two Variables Solution:
b=int(input("enter variable b”))#takes input for second
variable a=int(input("enter variable a"))#takes input for first
variable c=b #assigns value of b to c b=a #assigns value of b
to a a=c #assigns value of c to a print("a swapped is",a)

print("b swapped is",b)

Output:
enter variable a 4
enter variable b 6
a swapped is 6
4|Page
Python Programming for Artificial Intelligence (24CAI1101)

b swapped is 4
Result:

Program 1.c: ……………Convert Celsius to Fahrenheit…..………..


Objective: Write a program to convert Celsius to Fahrenheit Solution:

a=int(input("enter temperature in celsius")) #takes input in Celsius from


user b=(a* (9/5)) + 32 #converts Celsius to Fahrenheit
print("temperature in celcius is",b)

Output:
enter temperature in Celsius 37 temperature in

Fahrenheit is 98.60000000000001 Result:

Program 2.a: ……………Odd or Even …..………..


Objective: Write a Python Program to Check if a Number is Odd or Even
5|Page
Python Programming for Artificial Intelligence (24CAI1101)

Solution:
a=int(input("enter a number")) #takes number input from
user if a%2==0: #checks if number is even print("the
number is even") else :
print("the number is odd")
Output:
enter a number 3
the number is odd
Result:

Program 2.b: ……………Positive Negative or Zero…..………..


Objective:Write a Python Program to Check if a Number is Positive, Negative or 0
Solution:
a=int(input("enter a number")) #takes number input from
user if a>0: #checks if number is positive print("the
number is positive") elif a==0: #checks if number is zero
print("the number is zero") elif a<0:
#checks if number is less than 0
print("the number is negative")
Output:
enter a number 0 the
number is zero

6|Page
Python Programming for Artificial Intelligence (24CAI1101)

Result:

Program 2.c: ……………Armstrong Number…..………..


Objective: Write a Python Program to Check Armstrong Number Solution:
num = int(input("Enter a number: "))
sum = 0 temp
= num
while temp > 0: #runs loop while number is greater than
0 digit = temp % 10 sum += digit ** 3 temp //= 10 if
num == sum: print(num,"is an Armstrong number")
else: print(num,"is not an Armstrong number")

Output:
Enter a number: 34
34 is not an Armstrong number Result:

Program 3.a: ……………Fibonacci Number…..………..

7|Page
Python Programming for Artificial Intelligence (24CAI1101)

Objective: Write a Python Program to check if a number is fibonacci number?


Solution:
# Input the number to check
num = int(input("Enter a number to check if it's a Fibonacci number: "))

# Check if the number satisfies the Fibonacci condition


x1 = 5 * num * num + 4 x2
= 5 * num * num - 4

# Check if either x1 or x2 is a perfect square


# A number is a perfect square if its square root (when rounded down) squared equals the
number sqrt_x1 = int(x1 ** 0.5) sqrt_x2 = int(x2 ** 0.5)

if (sqrt_x1 * sqrt_x1 == x1) or (sqrt_x2 * sqrt_x2 == x2):


print(f"{num} is a Fibonacci number.") else:
print(f"{num} is not a Fibonacci number.")
Output:
Enter a number to check if it's a Fibonacci number: 21 21
is a Fibonacci number.
Result:

Program 3.b: ……………Cube of Natural Numbers…..………..


8|Page
Python Programming for Artificial Intelligence (24CAI1101)

Objective: Write a Python program to print cube sum of first n natural numbers.
Solution:
a=int(input("Enter a Number")) #takes input from
user b=1 su=0
for i in range(0,a+1): #iterates over each natural number till it reaches inputed
number b=i**3 #assigns the value of cubes to b su+=b #finds the value of sum
and assigns it to su print(su)
Output:
Enter a Number 5
225
Result:

Program 3.C: ……………Odd Numbers in a Range…..………..


Objective: Write a Python program to print all odd numbers in a range. Solution:
a=int(input("enter the starting point of range")) #takes starting input from user b=int(input("enter

the ending point of range")) #takes ending point input for range

for i in range(a,b+1): #iterates in range


if i%2==1: #checks if number is odd or not if yes then prints
it print("odd numbers are",i)
Output:
enter the starting point of range 3 enter
the ending point of range 17

9|Page
Python Programming for Artificial Intelligence (24CAI1101)

odd numbers are 3 odd


numbers are 5 odd
numbers are 7 odd
numbers are 9 odd
numbers are 11 odd
numbers are 13 odd
numbers are 15 odd
numbers are 17
Result:

Program 4.a: ……………Pascal Triangle…..………..


Objective: Write a Python Program to print Pascal Triangl Solution:
# Input number of rows
rows = int(input("Enter the number of rows: "))

# Initialize the triangle triangle


= []

for i in range(rows):
# Create a new row with fixed size
row = [0] * (i + 1) row[0] = 1 # First
element is always 1 row[i] = 1 # Last
element is always 1 if i > 1: for j
in range(1, i):

10 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

# Calculate value as sum of two elements above


row[j] = triangle[i-1][j-1] + triangle[i-1][j] triangle += [row]
# Manually adding the row to the triangle

# Calculate the maximum row width for


formatting max_width = rows * 2 for i in
range(rows):
# Convert the row elements to strings
manually row_str = "" for num in triangle[i]:
row_str += str(num) + " " # Remove trailing
space row_str = row_str[:-1]

# Format spacing by adding spaces manually


padding = " " * ((max_width - len(row_str)) // 2)
print(padding + row_str + padding)
Output:
Enter the number of rows: 4
1
11
121
1331
Result:

11 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Program 4.b: ……………Draw a pattern…..………..


Objective: Write a Python Program to draw a pattern for n numbers Solution:
# Input the number of rows
n = int(input("Enter the number of rows: "))
# Generate the pattern for
i in range(1, n + 1): for
j in range(n - i + 1):
print(i, end=" ")
print() # Move to the next line
Output:
Enter the number of rows: 5
11111
2222
333
44
5
Result:

Program 5.: ..………Capitalize First Letter of Each Word …..………..


Objective: Write a program with a function that accepts a string from keyboard and create a new string
after converting character of each word capitalized. For instance, if the sentence is “stop and smell the roses”
the output should be “Stop And Smell The Roses”

Solution:
a=input("enter a string")
#takes string input from user
b=a.title()

12 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

#converts first letter of each word to capital


print(b)
Output: enter a string this a
string to test case. This A String To
Test Case.
Result:

Program 6.a: ……………Reverse A List…..………..


Objective: Write a program that accepts a list from user. Your program should reverse the
content of list and display it. Do not use reverse () method. Solution:
a=list(input("enter elements of list"))
#takes list input from user

c=a[::-1]
#reverses the list and assigns it value to a print(c)

Output:
enter elements of list123457
['7', '5', '4', '3', '2', '1']

Result:
Program 6.b: ……………Largest In List …..………..

13 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Objective: Find and display the largest number of a list without using built-in function
#max (). Your program should ask the user to input values in list from keyboard. Solution:
a=list(map(int,input("enter numbers separated by space").split()))
#takes input from user separated by space

largest=a[0]
#assigns the largest to any value in list

for i in a:
#iterates over list

if i>largest:
#checks if number is larger than largest

largest=i
#assigns the largest number to largest

print(largest)

Output:
enter numbers separated by space23 45 67 56 1 90 56 89 90
Result:

Program 7: ……………Sum of rows of matrix…..………..


Objective: Find the sum of each row of matrix of size m x n Solution:
# Input: matrix size m x n m = int(input("Enter the
number of rows (m): ")) n = int(input("Enter the
number of columns (n): "))

# Initialize an empty matrix matrix


= []
14 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

# Input elements of the matrix print("Enter


the elements of the matrix:") for i in
range(m):
row = [] for j in range(n): row.append(int(input(f"Enter element
at position ({i+1}, {j+1}): "))) matrix.append(row)

# Calculate and display the sum of each row for i in range(m):


row_sum = sum(matrix[i]) # Calculate the sum of elements in the row
print(f"Sum of row {i+1} = {row_sum}")

Output:
= RESTART: C:\Users\Lenovo\Desktop\python_file\question7.py
Enter the number of rows (m): 3
Enter the number of columns (n): 4 Enter
the elements of the matrix:
Enter element at position (1, 1): 2
Enter element at position (1, 2): 11
Enter element at position (1, 3): 7
Enter element at position (1, 4): 12
Enter element at position (2, 1): 5
Enter element at position (2, 2): 2
Enter element at position (2, 3): 9
Enter element at position (2, 4): 15
Enter element at position (3, 1): 8
Enter element at position (3, 2): 3
Enter element at position (3, 3): 10
Enter element at position (3, 4): 42
Sum of row 1 = 32
Sum of row 2 = 31

15 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Sum of row 3 = 63
Result:

Program 8.a: ……………Number of uppercase, Lowercase ,numeric digits and


Spaces in a string …..………..
Objective: a) Write a program that reads a string from keyboard and display:
* The number of uppercase letters in the string.
* The number of lowercase letters in the string.
* The number of digits in the string.
* The number of whitespace characters in the string Solution:
a=input("enter a string")
upper=0 lower=0
number=0
space=0
up="QWERTYU
IOPASDFGHJK
LZXCVBNM"
16 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

#All the capital letters are stored in up

lo="qwertyuiopasdfghjklzxcvbnm"
#All the small letters are stored in lo

nu="1234567890"
#All the numbers are stored in lu

sp=" "
#All the spaces are stored in sp

for i in a:
if i in up:
#checks how many capital letters in string
upper+=1
#counts how many capital letters in string
elif i in lo:
#checks how many small letters in string

lower+=1
#counts how many small letters in string
elif i in nu:
#checks how many numbers letters in string

number+=1 #counts how many


numbers in string elif i in sp:
#checks how many spaces in string

space+=1
#counts how many spaces in string

print("number of lower case letters",lower) print("number


of upper case letters",upper) print("number of numbers
",number)
print("number of spaces",space)
Output: enter a string Hello I am
12 Years Old. number of lower case
letters 12 number of upper case letters
4
number of numbers 2

17 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

number of spaces 5
Result:

Program 8.b: ……………Common in two strings …..………..


Objective: Python Program to Find Common Characters in Two Strings. Solution:
# Input strings
string1 = input("enter string") string2
= input("enter string 2")
# Convert the second string to a set for faster lookup set2
= set(string2)
# List to store common characters common_characters
= []
# Loop through each character in the first string for
char in string1: if char in set2 and char not in
common_characters:
common_characters.append(char)
Output:
enter string Hello enter
string 2 Bye
Common characters: [' ', 'e']
Result:

Program 8.c: ……………Count Number of Vowels …..………..

18 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Objective: Python Program to Count the Number of Vowels in a String. Solution:


a=input("enter a string")
vo="aeiou" v=0 for i in
a: if i in vo: v+=1
print(i,"are vowels")
print(v,"are number of vowels")
Output:
enter a string hello myself a Student
e are vowels o are vowels e are
vowels a are vowels u are vowels e
are vowels
6 are number of vowels
Result:

Program 9.: ……………Check Element in Tuples of Tuples…..………..


Objective: a) Write a Python program to check if a specified element presents in a tuple of
tuples. Original list:
((‘Red’ ,’White’ , ‘Blue’),(‘Green’, ’Pink’ , ‘Purple’), (‘Orange’, ‘Yellow’, ‘Lime’)) Check
if White present in said tuple of tuples!
True
Check if Olive present in said tuple of tuples! False

Solution:
# Original tuple of tuples
tuples = (('Red', 'White', 'Blue'), ('Green', 'Pink', 'Purple'), ('Orange', 'Yellow', 'Lime'))

# Check if an element is present


element1 = 'White' element2 =
'Olive'
19 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

# Search for element1


found1 = False for
sub_tuple in tuples: if
element1 in sub_tuple:
found1 = True
break
print(f"Check if {element1} present in said tuple of tuples!") print(found1)
: if element2 in
sub_tuple: found2 =
True

# Search for element2


found2 = False for
sub_tuple in tuples
break
print(f"Check if {element2} present in said tuple of tuples!") print(found2)
Output:
Check if White present in said tuple of tuples!
True
Check if Olive present in said tuple of tuples!
False
Result:

Program 9.b: ……………Remove empty tuples…..………..


Objective:Find the sum of each row of matrix of size m x n Solution:
# Sample data
data = [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]

# Remove empty tuples filtered_data = [] for


item in data: if item != (): # Check if the
tuple is not empty
filtered_data.append(item)

20 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

# Print the result


print("Expected output:", filtered_data)
Output:
Expected output: [('',), ('a', 'b'), ('a', 'b', 'c'), 'd']
Result:

Program 10: ………….Difference between 2 lists…..………..


Objective: Write a Program in Python to Find the Differences Between Two Lists Using
Sets.

Solution:
# Input lists list1 =
map(int,input().split())
list2=map(int,input().split())

# Convert lists to
sets set1 = set(list1)
set2 = set(list2)

# Find differences diff1 = set1 - set2 # Elements in


list1 but not in list2 diff2 = set2 - set1 # Elements in
list2 but not in list1

# Convert results back to lists for display


diff1_list = list(diff1) diff2_list
= list(diff2)

# Print the results print("Differnce of list2


from list1", diff1_list)
print("Differnce of list1 from list2:", diff2_list)
Output:
Enter list123 45 89 67 23 56 21
Enter list256 45 23 84 09
21 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Differnce of list2 from list1 [89, 67, 21]


Differnce of list1 from list2: [9, 84]
Result:

Program 11.a: ……………Remove duplicates from dictionary…..………..


Objective:Write a Python program Remove duplicate values across Dictionary Values.
Input : test_dict = {‘Manjeet’: [1], ‘Akash’: [1, 8, 9]}
Output : {‘Manjeet’: [], ‘Akash’: [8, 9]}
Input : test_dict = {‘Manjeet’: [1, 1, 1], ‘Akash’: [1, 1, 1]}
Output : {‘Manjeet’: [], ‘Akash’: []}

Solution:
# Input dictionary from the user n =
int(input("Enter the number of keys: "))
test_dict = {}

for _ in range(n): key = input("Enter key: ") values =


input("Enter values separated by spaces: ").split() values =
[int(val) for val in values] # Convert input to integers
test_dict[key] = values

#Initialize an empty list to keep track of seen values seen_values


= []

# Create an empty dictionary for the result result


= {}

# Process each key and its list of values for key in test_dict:
new_values = [] # Temporary list to store non-duplicate values
for value in test_dict[key]:
# Add the value only if it hasn't been seen before
if value not in seen_values: new_values +=

22 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

[value] # Add value to the new list seen_values


+= [value] # Mark it as seen
# Update the result dictionary
result[key] = new_values

# Print the output print("Output:",


result)
Output:
Enter the number of keys: 2
Enter key: Manjeet
Enter values separated by spaces: 1
Enter key: Akash
Enter values separated by spaces: 1 8 9
Output: {'Manjeet': [1], 'Akash': [8, 9]}
Result:

Program 11.b: ……………Count frequencies in list…..………..


Objective:Write a Python program to Count the frequencies in a list using dictionary in
Python.
Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,4, 4, 4, 2, 2, 2, 2]
Output :
1:5
2:4
3:3
4:3
5:2
Explanation : Here 1 occurs 5 times, 2 occurs 4 times and so on... Solution:
# Input list
23 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

input_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]

# Initialize an empty dictionary to store frequencies


frequency_dict = {}

# Count frequencies
for element in input_list: if element in frequency_dict: frequency_dict[element]
+= 1 # Increment count if element exists in the dictionary else:
frequency_dict[element] = 1 # Initialize count to 1 if element is not in the dictionary

# Print the output print("Output:") for


key, value in frequency_dict.items():
print(f"{key} : {value}")
Output:
Output:
1:5
5:2
3:3
4:3
2:4
Result:

Program 12.a: ……………Capitalize first letter…..………..


Objective:Write a Python Program to Capitalize First Letter of Each Word in a File.
Solution:
file_name = input("Enter the file name: ")

try:

24 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

# Open the file in read mode


with open(file_name, 'r') as file:
# Read the content of the file
content = file.read()
# Split the content into words, capitalize each word, and join them back into a string
capitalized_content = ' '.join([word.capitalize() for word in content.split()])

# Open the file in write mode and save the updated content with
open(file_name, 'w') as file: file.write(capitalized_content)
print(f"First letter of each word in '{file_name}' has been capitalized.")

except FileNotFoundError:
print(f"The file '{file_name}' does not exist.")
except Exception as e: print(f"An error
occurred: {e}")

Output:
Enter the file name: testpad.txt
First letter of each word in 'testpad.txt' has been capitalized.
Result:

Program 12.b: ……………Print in reverse order…..………..

25 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Objective: Write a Python Program to Print the Contents of File in Reverse Order.
Solution:
# Input the file name
file_name = input("Enter the file name: ")

try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read all lines of the file lines
= file.readlines()

# Print the contents in reverse order with each line reversed


print("Contents of the file in reverse order with each line reversed:") for
line in reversed(lines):
print(line.strip()[::-1]) # Reverse each line and strip extra newlines

except FileNotFoundError:
print(f"The file '{file_name}' does not exist.") except
Exception as e:
print(f"An error occurred: {e}")
Output:
Enter the file name: testpad.txt
Contents of the file in reverse order with each line reversed:
.margorP ehT kcehC oT tnemetatS tseT A sI sihT
Result:

Program 13.: ……………Catch an Exception…..………..

26 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Objective:WAP to catch an exception and handle it using try and except code blocks.
Solution:
try:
# Ask user for input and convert it to an integer
num1 = int(input("Enter the first number: ")) num2
= int(input("Enter the second number: ")) #
Perform division result = num1 / num2
print(f"The result of {num1} divided by {num2} is: {result}")

except ZeroDivisionError:
# This block will run if the user tries to divide by zero
print("Error: You cannot divide by zero!")

except ValueError:
# This block will run if the user does not enter a valid integer
print("Error: Invalid input. Please enter valid integers.")

except Exception as e:
# This block will catch any other exception
print(f"An unexpected error occurred: {e}")

Output:
= RESTART: C:\Users\Lenovo\Desktop\python_file\question13.py
Enter the first number: 8
Enter the second number: 6
The result of 8 divided by 6 is: 1.3333333333333333

========== RESTART: C:\Users\Lenovo\Desktop\python_file\question13.py ==========


Enter the first number: 8
Enter the second number: 0 Error:
You cannot divide by zero!

========== RESTART: C:\Users\Lenovo\Desktop\python_file\question13.py ==========


Enter the first number: 8
Enter the second number: i
Error: Invalid input. Please enter valid integers.

27 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

========== RESTART: C:\Users\Lenovo\Desktop\python_file\question13.py ==========


Enter the first number:
Error: Invalid input. Please enter valid integers.
Result:

Program 14.: ……………Append, delete and display elements…..………..


Objective:Write a Python Program to Append, Delete and Display Elements of a
List using Classes. Solution: class ListOperations:
# Initialize an empty list directly in the class
my_list = []

# Create an instance of ListOperations list_ops


= ListOperations()

# Append elements to the list


list_ops.my_list.append(10) list_ops.my_list.append(20)
list_ops.my_list.append(30)

28 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

# Display the list after appending elements print("Current


List:", list_ops.my_list)
# Delete an element from the list if
20 in list_ops.my_list:
list_ops.my_list.remove(20) print("Element '20'
has been removed from the list.") else:
print("Element '20' not found in the list.")

# Display the list after deleting an element print("List


after deletion:", list_ops.my_list)

# Try deleting an element that doesn't exist if


50 in list_ops.my_list:
list_ops.my_list.remove(50) print("Element '50'
has been removed from the list.") else:
print("Element '50' not found in the list.")

# Final list display print("Final


List:", list_ops.my_list)
Output:
= RESTART: C:/Users/Lenovo/Desktop/python_file/question14.py
Current List: [10, 20, 30]
Element '20' has been removed from the list. List
after deletion: [10, 30]
Element '50' not found in the list.
Final List: [10, 30]
Result:

Program 15.: …………Area and Perimeter of a circle……..………..


Objective:Write a Python Program to Find the Area and Perimeter of the Circle using
Class.

29 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Solution:
class Circle:
# Constructor to initialize radius
def __init__(self, radius):
self.radius = radius

# Method to calculate area of the circle def


area(self): return 3.14159 * (self.radius ** 2) #
Area = π * r^2

# Method to calculate perimeter (circumference) of the circle def


perimeter(self): return 2 * 3.14159 * self.radius # Perimeter
(Circumference) = 2 * π * r

# Input the radius of the circle


radius = float(input("Enter the radius of the circle: "))

# Create an instance of the Circle class circle


= Circle(radius)

# Calculate and display the area and perimeter print(f"Area


of the circle: {circle.area():.2f}")
print(f"Perimeter (Circumference) of the circle: {circle.perimeter():.2f}")
Output:
= RESTART: C:/Users/Lenovo/Desktop/python_file/question15.py
Enter the radius of the circle: 4
Area of the circle: 50.27
Perimeter (Circumference) of the circle: 25.13
Result:

Program 16.: …………Interactive Application……..………..

30 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

Objective:Create an interactive application using Python's Tkinter library for graphics


programming.. Solution:
import tkinter as tk from tkinter
import messagebox

def click_button(value):
if value == "=":
try:
result = eval(entry.get()) entry.delete(0,
tk.END) entry.insert(tk.END, str(result))
except Exception as e:
messagebox.showerror("Error", "Invalid Input") elif
value == "C": entry.delete(0, tk.END) else:
entry.insert(tk.END, value) app
= tk.Tk()
app.title("Interactive Calculator")
app.geometry("300x400") app.resizable(False,
False)

# Create an entry widget


entry = tk.Entry(app, font=("Arial", 18), bd=10, insertwidth=2, width=14, borderwidth=4, justify="right")
entry.grid(row=0, column=0, columnspan=4)

# Button buttons
=[
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
]

row_val = 1 col_val
=0

# Create buttons dynamically for


button in buttons:
button_widget =
tk.Button( app,
text=button, padx=20,
pady=20, font=("Arial",
14),
bg="lightgray",
command=lambda b=button: click_button(b)
31 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

)
button_widget.grid(row=row_val, column=col_val, sticky="nsew")
col_val += 1 if col_val > 3: col_val = 0 row_val += 1

# Adjust row and column for


i in range(5):
app.grid_rowconfigure(i, weight=1) for
i in range(4):
app.grid_columnconfigure(i, weight=1)

# Run the application app.mainloop()

Output:
/usr/local/bin/python3 "/Users/yuvrajsharma/Desktop/python final file. /programme4a.py"
yuvrajsharma@Yuvrajs-MacBook-Pro python final file. % /usr/local/bin/python3 "/Users/yuvrajsharma/
Desktop/python final file. /programme4a.py"

2024-11-24 20:52:04.447 Python[4956:282165] +[IMKClient subclass]: chose IMKClient_Legacy 2024-11-24


20:52:04.447 Python[4956:282165] +[IMKInputSession subclass]: chose IMKInputSession_Legacy Result:

32 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

33 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

34 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

35 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

36 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

37 | P a g e
Python Programming for Artificial Intelligence (24CAI1101)

38 | P a g e

You might also like