[go: up one dir, main page]

0% found this document useful (0 votes)
52 views40 pages

QWERT

Uploaded by

sidaksingh269
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)
52 views40 pages

QWERT

Uploaded by

sidaksingh269
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/ 40

Practical File

Of
Python Programming
Using Artificial
Intelligence
24CAI1101
Submitted

in partial fulfillment for the award of the degree

of

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

Anand Singh Nitin Singh


Yadav (CSE-AI) 2410993432
Chitkara University, Punjab 1st sem,(2024-2028),G-35
INDEX

Sr. Practical Name Page Teacher


No Number Signature
1. a) Write a Python Program to Calculate the Area of a
Triangle. 4-5
b) Write a Python Program to Swap two Variables.
c) Write a Python Program to Convert Celsius to
Fahrenheit.
2. a.) Write a Python Program to Check if a Number is Odd
or Even.
b.) Write a Python Program to Check if a Number is 6-7
Positive, Negative or 0.
c.) Write a Python Program to Check Armstrong Number.

3. a.) Write a Python program to check if a given number is


Fibonacci number?
b.) Write a Python program to print cube sum of first n 8-9
natural numbers.
c.) Write a Python program to print all odd numbers in a
range.
4. a.) Write a Python Program to Print Pascal Triangle
b.) WAP to Draw the following Pattern for n number:
11111 10-11
2222
333
44
5
5. 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 12-13
sentence is “stop and smell the roses” the output should
be “Stop And Smell The Roses”
6. a.) 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.
b) Find and display the largest number of a list without 14-15
using built-in function
max (). Your program should ask the user to input values
in list from keyboard.
7. Find the sum of each row of matrix of size m x n. 16-17
8. a) Write a program that reads a string from keyboard and
display: 18-19
* 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.
b) Python Program to Find Common Characters in Two
Strings. 20-21
c) Python Program to Count The Number of Vowels in a
String.

9. a) Write a Python program to check if a specified element


presents in a tuple of tuples. 22-23
b) Write a Python program to remove an empty tuple(s)
from a list of tuples.
10. a) Write a Program in Python to Find the Differences
Between Two Lists Using Sets. 24-25
11. a) Write a Python program Remove duplicate values 26-27
across Dictionary Values.
b) Write a Python program to Count the frequencies in a 28-29
list using dictionary in Python.
12. a) Write a Python Program to Capitalize First Letter of
Each Word in a File. 30-31
b.) Write a Python Program to Print the Contents of File
in Reverse Order.
13. Write program to catch an exception and handle it using 32-33
try and except code blocks.
14. Write a Python Program to Append, Delete and Display 34-35
Elements of a List using Classes.
15. Write a Python Program to Find the Area and Perimeter 36-37
of the circle using Class.
16. Create an interactive application using Python's Tkinter 38-40
library for graphics programming.
Program 1(a): Write a Python Program to Calculate the Area of a Triangle.

Solution:

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


height = float(input("Enter the height of the triangle: "))
if base < 0 or height < 0:
print("Base and height must be non-negative numbers.")
else:
area = 0.5 * base * height
print(f"The area of the triangle is: {area}")

Program 1(b): Write a Python Program to Swap Two Variables.


Solution:
a= input("Enter the first variable (a): ")
b = input("Enter the second variable (b): ")
print ("First variable (a) before swapping =", a)
print ("Second variable (b) before swapping =", b)
temp = a
a=b
b = temp
print ("First variable (a) after swapping =", a)
print ("Second variable (b) after swapping =", b)

Program 1(c): Write a Python Program to Convert Celsius To Fahrenheit.


Solution:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")
Program 1(a): Title of program: Python Program to Calculate the Area of a Triangle.
OUTPUT:

Program 1(b): Title of program: Write a Python Program to Swap Two Variables.

OUTPUT:
Program 1(c): Title of program: Write a Python Program to Convert Celsius to Fahrenheit .
OUTPUT:
Program 2(a): Write a Python Program to Check if a Number is Odd or Even.
Solution:
number=int(input("enter any number:"))

if number%2==0:
print("Even number")
else:
print("odd number")

Program 2(b): Write a Python Program to Check if a Number is Positive, Negative or 0.

Solution:

num=int(input("Enter a number :"))


if num>0:
print("The number is positive")
elif num<0:
print("the number is negative")
else:
print("The number is zero")

Program 2(c): Write a Python Program to Check Armstrong Number.

Solution:
num= int(input("Enter a number: "))
sum=0
temp=num
while temp>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: Program 2(a): Write a Python Program to Check if a Number is Odd or Even.

OUTPUT: Program 2(b): Write a Python Program to Check if a Number is Positive, Negative or 0 .

OUTPUT: Program 2(c): Write a Python Program to Check Armstrong Number.

Output:
Program 3(a): Write a Python program to check if a given number is Fibonacci number?

Solution:

num=int(input("Enter the number: "))


temp=1
k=0
a=0
summ=0
while summ<=num:
summ=temp+k
temp=summ
k=temp
if summ==num:
a=a+1
print("Yes. {} is a fibonnaci number".format(num))
break
if a==0:
print("No. {} is NOT a fibonacci number".format(num))

Program 3(b): Write a Python program to print cube sum of first n natural numbers.

Solution:

n=int(input("Enter The Number: "))


sum_n=(n * (n + 1) // 2) ** 2
print(sum_n)

Program 3(c): Write a Python program to print all odd numbers in a range.

Solution:

start = int(input("Enter the start of the range: "))


end = int(input("Enter the end of the range: "))
odd_numbers = [num for num in range(start, end + 1) if num % 2 != 0]
print(f"Odd numbers in the range {start} to {end}: {odd_numbers}")
Program 3(a): Title of program : Write a Python program to check if a given number is
Fibonacci number?
OUTPUT:

Program 3(b): Title of program : Write a Python program to print cube sum of first n natural
numbers.
OUTPUT:

Program 3(c): Title of program : Write a Python program to print all odd numbers in a range.
OUTPUT:
Program 4 (a): Write a Python Program to Print Pascal Triangle.

Solution:

def print_pascals_triangle(rows):
for i in range(rows):
print(' ' * (rows - i), end='')
num = 1
for j in range(i + 1):
print(num, end=' ')
num = num * (i - j) // (j + 1)
print()
num_rows = int(input("Enter number of rows: "))
print_pascals_triangle(num_rows)

Program 4 (b): WAP to Draw the following Pattern for n number:


11111
2222
333
44
5

Solution:

def print_pattern(n):
for i in range(1, n+1):
for j in range(1, i+1):
print(i, end=' ')
print()
# Example usage
n = int(input("Enter the number of rows: "))
print_pattern(n)
Program 4(a): Title of program: Write a Python Program to Print Pascal Triangle.

OUTPUT:

Program 4(b): Title of program: WAP to Draw the following Pattern for n number:
11111
2222
333
44
5

OUTPUT:
Program 5: 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:
def words(sentence):
return ' '.join(word.capitalize() for word in sentence.split())

# Example usage
sentence = input("Enter a sentence: ")
print(words(sentence))
Program 5: Title of program: 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”.

OUTPUT:
Program 6(a): 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:

def reverse_list(input_list):
reversed_list = []
for i in range(len(input_list) - 1, -1, -1):
reversed_list.append(input_list[i])
return reversed_list

user_input = input("Enter a list of elements separated by commas: ")


input_list = [item.strip() for item in user_input.split(',')]
reversed_output = reverse_list(input_list)
print("Reversed list:", reversed_output)

Program 6(b): 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:

def find_largest_number(input_list):
largest = input_list[0]
for number in input_list:
if number > largest:
largest = number
return largest
user_input = input("Enter a list of numbers separated by commas: ")
input_list = [int(item.strip()) for item in user_input.split(',')]
largest_number = find_largest_number(input_list)
print("The largest number is:", largest_number)
Program 6(a): Title of program: 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.
OUTPUT:

Program 6(b): Title of program: 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.
OUTPUT:
Program 7: Find the sum of each row of matrix of size m x n. For example, for the
following matrix output will be like this:

Sum of row 1 = 32
Sum of row 2 = 31
Sum of row 3 = 63

Solution:

matrix=[
[2,11,7,12],
[5,2,9,15],
[8,3,10,42]
]
sum1=matrix[0][0]+matrix[0][1]+matrix[0][2]+matrix[0][3]
sum2=matrix[1][0]+matrix[1][1]+matrix[1][2]+matrix[1][3]
sum3=matrix[2][0]+matrix[2][1]+matrix[2][2]+matrix[2][3]
print("Sum of row 1 =",sum1)
print ("Sum of row 2 =",sum2)
print("Sum of row 3 =",sum3)
Program 7: Title of program: Find the sum of each row of matrix of size m x n. For example,
for the following matrix output will be like this:

Sum of row 1 = 32
Sum of row 2 = 31
Sum of row 3 = 63

OUTPUT:
Program 8(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:

def read_string():
text = input('Enter a string: ')
lower = upper = digit = space = 0

for ch in text:
if ch.isupper():
upper += 1
elif ch.islower():
lower += 1
elif ch.isdigit():
digit += 1
elif ch == ' ':
space += 1

print('The number of uppercase letters:', upper)


print('The number of lowercase letters:', lower)
print('The number of digits:', digit)
print('The number of whitespace characters:', space)

read_string()
Program 8(a): Title of program: 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.

OUTPUT:
Program 8 (b): Python Program to Find Common Characters in Two Strings.
Solution:
def common(str1,str2):
for i in str1:
for j in str2:
if i==j:
print(i,end=" ")

a=input("enter a string: ")


b=input("enter a string: ")

common(a,b)
Program 8 (c): Python Program to Count the Number of Vowels in a String.

Solution:

def count_vowels():
s=input("Enter a string :")
vowels=0
for i in s:
if(i=='a' or i=='i' or i=='e' or i=='o' or i=='u' or i=='A' or i=='I' or i=='E' or i=='O' or
i=='U' ):
vowels= vowels+1

print("Numbers of vowels are :")


print(vowels)
count_vowels()
Program 8(b): Title of program: Python Program to Find Common Characters in
Two Strings.

OUTPUT:

Program 8(c): Title of program: Python Program to Count the Number of Vowels
in a String.

OUTPUT:
Program 9(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:

def check_element_in_tuples(tuples, element):


for inner_tuple in tuples:
if element in inner_tuple:
return True
return False
original_tuples = (('Red', 'White', 'Blue'),
('Green', 'Pink', 'Purple'),
('Orange', 'Yellow', 'Lime'))
check1 = check_element_in_tuples(original_tuples, 'White')
check2 = check_element_in_tuples(original_tuples, 'Olive')
print(f"Check if 'White' present in said tuple of tuples: {check1}")
print(f"Check if 'Olive' present in said tuple of tuples: {check2}")

Program 9(b): Write a Python program to remove an empty tuple(s) from a list of tuples.
Sample data: [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
Expected output: [('',), ('a', 'b'), ('a', 'b', 'c'), 'd']

Solution:

def remove_empty_tuples(tuples_list):
return [t for t in tuples_list if t]
sample_data = [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d',)]
result = remove_empty_tuples(sample_data)
print(result)
Program 9(a): Title of program: 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

OUTPUT:

Program 9(b): Title of program: Write a Python program to remove an empty tuple(s) from a
list of tuples.
Sample data: [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
Expected output: [('',), ('a', 'b'), ('a', 'b', 'c'), 'd']

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

Solution:

list1 = ['1','2','3','4','5']
list2 = ['2','4','5']
set1 = set(list1)
set2 = set(list2)
list3 = list(set1.symmetric_difference(set2))
print(list3)
Program 10: Title of program: Write a Program in Python to Find the Differences
Between Two Lists Using Sets.

OUTPUT:
Program 11 (a): 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:

def remove_duplicates(test_dict):
seen = set()
duplicates = set()

for values in test_dict.values():


for value in values:
if value in seen:
duplicates.add(value)
else:
seen.add(value)

result = {key: [value for value in values if value not in duplicates] for key, values in
test_dict.items()}

return result

test_dict1 = {'Manjeet': [1], 'Akash': [1, 8, 9]}


test_dict2 = {'Manjeet': [1, 1, 1], 'Akash': [1, 1, 1]}

print(remove_duplicates(test_dict1))
print(remove_duplicates(test_dict2))
Program 11(a): Title of program: 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’: []}

OUTPUT:
Program 11(b): 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:
def count_frequencies(input_list):
frequency_dict = {}
for number in input_list:
if number in frequency_dict:
frequency_dict[number] += 1
else:
frequency_dict[number] = 1
return frequency_dict
input_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
frequencies = count_frequencies(input_list)
for number, count in frequencies.items():
print(f"{number} : {count}")
Program 11(b): Title of program: 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...
OUTPUT:
Program 12(a): Write a Python Program to Capitalize First Letter of Each Word in a File.
Solution:

def capitalize_first_letter_of_each_word(input_string):
capitalized_string = input_string.title()
return capitalized_string
if name == " main ":
input_string =input("enter something: ")
result = capitalize_first_letter_of_each_word(input_string)
print(result)

Program 12(b): Write a Python Program to Print the Contents of File in Reverse Order.
Solution:
def reverse_string(input_string):
reversed_string = input_string[::-1]
return reversed_string

if name == " main ":


input_string =input("enter something: ")
result = reverse_string(input_string)
print(result)
Program 12(a): Title of Program: Write a Python Program to Capitalize First
Letter of Each Word in a File.
OUTPUT:

Program 12(b): Write a Python Program to Print the Contents of File in Reverse
Order.
OUTPUT:
Program 13: WAP to catch an
exception and handle it using try and except code blocks.
Solution:
def integer():
while True:
try:
n = int(input("ENTER A VALID INTEGER: "))
print("You entered the integer: ",n)
break
except ValueError:
print("That's not a valid integer. Please try again.")
integer()
Program 13: Title of Program: WAP to catch an exception and handle it using
try and except code blocks.
OUTPUT:
Program 14: Write a Python Program to Append, Delete and Display Elements
of a List using Classes.
Solution:

def app(a):
x=int(input("ENTER THE NUMBER TO BE AAPENDED: "))
a.append(x)
print("LIST AFTER APPENDING:",a)
def delete(a):
x=int(input("ENTER THE NUMBER YOU WANT TO DELETE: "))
a.remove(x)
print("LIST AFTER DELETION:",a)

list=[]
n=int(input("ENTER THE NUMBER OF ELEMENTS"))
for i in range(n):
x=int(input())
list.append(x)
print("ORIGINAL LIST:",list)
app(list)
delete(list)
Program 14: Title of Program: Write a Python Program to Append, Delete and
Display Elements of a List using Classes.
OUTPUT:
Program 15: Write a Python Program to Find the Area and Perimeter of the
Circle using Class.
Solution:

def area(n):
return (3.14)*r*r
def per(m):
return 2*(3.14)*r
r=float(input("ENTER THE RADIUS OF THE CIRCLE: "))
j=area(r)
k=per(r)
print("AREA OF CIRCLE:",j)
print("PERIMETER OF CIRCLE:",k)
Program 15: Title of Program: Write a Python Program to Find the Area and
Perimeter of the Circle using Class.
OUTPUT:
Program 16: Create an interactive application using Python's Tkinter library
for graphics programming.
Solution:

import tkinter as tk
from tkinter import colorchooser

# Initialize the main application window


root = tk.Tk()
root.title("Interactive Graphics Application")
root.geometry("600x500")

# Global variables
current_color = "black"
current_shape = "circle"

# Function to change color using a color picker dialog


def change_color():
global current_color
color = colorchooser.askcolor()[1]
if color:
current_color = color
color_button.config(bg=color)

# Function to set the shape to circle


def set_circle():
global current_shape
current_shape = "circle"

# Function to set the shape to square


def set_square():
global current_shape
current_shape = "square"

# Function to clear the canvas


def clear_canvas():
canvas.delete("all")
# Function to draw shapes on mouse click
def draw_shape(event):
x, y = event.x, event.y
size = 30 # Size of the shape

if current_shape == "circle":
canvas.create_oval(x - size, y - size, x + size, y + size, fill=current_color, outline="")
elif current_shape == "square":
canvas.create_rectangle(x - size, y - size, x + size, y + size, fill=current_color, outline="")

# Creating a canvas for drawing


canvas = tk.Canvas(root, bg="white")
canvas.pack(fill="both", expand=True)
canvas.bind("<Button-1>", draw_shape)

# Color change button


color_button = tk.Button(root, text="Choose Color", command=change_color, bg=current_color)
color_button.pack(side="left", padx=10, pady=10)

# Shape selection buttons


circle_button = tk.Button(root, text="Circle", command=set_circle)
circle_button.pack(side="left", padx=10, pady=10)

square_button = tk.Button(root, text="Square", command=set_square)


square_button.pack(side="left", padx=10, pady=10)

# Clear button
clear_button = tk.Button(root, text="Clear", command=clear_canvas)
clear_button.pack(side="left", padx=10, pady=10)

# Run the main application loop


root.mainloop()
OUTPUT:

You might also like