0% found this document useful (0 votes)
16 views63 pages

Python Programs for BCA Course Tasks

The document contains a series of Python programming problems and their solutions, authored by Krishna Singh, for a BCA (AI & DS) course. Each problem addresses a specific programming concept, such as data types, variable swapping, finding the greatest of three numbers, leap year checking, and more, providing source code and output examples. The problems aim to enhance understanding of fundamental programming principles and algorithms.

Uploaded by

krishkhati777
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)
16 views63 pages

Python Programs for BCA Course Tasks

The document contains a series of Python programming problems and their solutions, authored by Krishna Singh, for a BCA (AI & DS) course. Each problem addresses a specific programming concept, such as data types, variable swapping, finding the greatest of three numbers, leap year checking, and more, providing source code and output examples. The problems aim to enhance understanding of fundamental programming principles and algorithms.

Uploaded by

krishkhati777
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

NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 1: Write a python program to demonstrate basic data types of


python

and the concept of object identity.

OBJECTIVE: To understand the implementation of various data type in python.

DESCRIPTION: A data type in programming refers to the kind of data that a variable can
hold.

SOURCE CODE:

a=10

print("value of variable a=",a)

print("class type of a=",type(a))

print("ID of variable a=",id(a))

x="tiya"

print("name of variable x=",x)

print("class type of variable x=",type(x))

print("ID of variable a=",id(x))

y=2.4

print("value of variable y=",y)

print("class type of variable y=",type(y))

print("ID of variable y=",id(y))

z=3+2j

print("value of variable z=",z)

print("class type of variable z=",type(z))

print("ID of variable z=",id(z))


l1=["nikk","sonam","binni"]

print("value of l1=",l1)

print("class type of l1=",type(l1))

print("ID of l1=",id(l1))

t1=("ginni","rashi")

print("value of t1=",t1)

print("class type of t1=",type(t1))

print("ID of variable t1=",id(t1))

r1=(1,2,3,4)

print("value of r1=",r1)

print("class type of r1=",type(r1))

print("ID of r1=",id(r1))

m1={"name":"John","age":23}

print("value of m1=",m1)

print("class type of m1=",type(m1))

print("ID of m1=",id(m1))

b1=True

print("value of b1=",b1)

print("calss type of b1=",type(b1))

print("ID of b1=",id(b1))

OUT PUT

value of variable a= 10

class type of a= <class 'int'>

ID of variable a= 140703357629640

name of variable x= tiya

class type of variable x= <class 'str'>

ID of variable a= 2269711611344

value of variable y= 2.4


class type of variable y= <class 'float'>

ID of variable y= 2269708792208

value of variable z= (3+2j)

class type of variable z= <class 'complex'>

ID of variable z= 2269711554736

value of l1= ['nikk', 'sonam', 'binni']

class type of l1= <class 'list'>

ID of l1= 2269709705856

value of t1= ('ginni', 'rashi')

class type of t1= <class 'tuple'>

ID of variable t1= 2269711383936

value of r1= (1, 2, 3, 4)

class type of r1= <class 'tuple'>

ID of r1= 2269709497056

value of m1= {'name': 'John', 'age': 23}

class type of m1= <class 'dict'>

ID of m1= 2269711690240

value of b1= True

class type of b1= <class 'bool'>

ID of b1= 140703356744112

NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 2 Write a python program to swap to two variable using


arithmetic

operator only.
OBJECTIVE-To write a Python program that swaps the values of two variables without
using a

third variable or built-in swap methods, but instead using arithmetic operators.

DESCRIPTION-This program demonstrates how to interchange (swap) the values of two

variables using addition and subtraction (or alternatively, multiplication and division).

SOURCE CODE

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

b = int(input("Enter second number: "))

print("Before swapping:")

print("a =", a)

print(“b=”,b)

a=a+b

b=a-b

a=a-b

print("After swapping:")

print("a =", a)

print("b =", b)

OUTPUT

Enter first number: 10

Enter second number: 5

Before swapping:

a = 10 , b = 5

After swapping:

a=5,b=1
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 3 Write a Python program to find the greatest of three numbers
and

arrange the numbers in ascending order.

OBJECTIVE-To find the greatest of three numbers and display the numbers in ascending
order.

DESCRIPTION-This program takes three numbers as input, compares them to


determine the

greatest number, and then arranges all three numbers in ascending order using simple

[Link] or sorting

SOURCE CODE-

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

c = float(input("Enter third number: "))

if a >= b and a >= c:

greatest = a

elif b >= a and b >= c:

greatest = b

else:

greatest = c

print("\nThe greatest number is:", greatest)

numbers = [a, b, c]
[Link]()

print("Numbers in ascending order:", numbers)

OUTPUT

Enter first number: 15

Enter second number: 9

Enter third number: 21

The greatest number is: 21

Numbers in ascending order: [9.0, 15.0, 21.0]


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 4 Write a python program to print whether a given year is leap
year

or not.

OBJECTIVE-To check whether the entered year is a leap year or not

DESCRIPTION-This program takes a year as input and determines if it’s a leap year.

A year is a leap year if:

It is divisible by 4,

But not divisible by 100,

Except when it is also divisible by 400.

SOURCE CODE:

year=int(input("Enter a year:"))

if(year%4==0 and year%100!=0) or(year%400==0):

print(f"{year}is a leap year.")

else:

print(f"{year}is not a leap year")

OUTPUT:

Enter a year:2024

2024is a leap year.


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 5: Write a program to check whether the number is even or odd.

OBJECTIVE: To determine whether a given number is even or odd.

EXPLAINATION: This program takes an integer an integer as input and check if it is


divisible

by 2. -If the remainder is 0, the number is even. -Otherwise, it is odd.

SOURCE CODE:

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

if num%2==0:

print("The number is Even.")

else:

print("The number is Odd.")

OUTPUT:

Enter a number:5

The number is Odd.


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 6: Write a program to calculate factorial of a given number.

OBJECTIVE: To calculate the factorial of a given number using a loop.

EXPLAINATION: This program takes an integer as input and finds its factorial.

The factorial of a number n (written as n!) is the product of all positive integer from 1 to
n.

SOURCE CODE:

n = int(int(input("enter the number:-")))

prod = 1

for i in range(1, n + 1, 1):

prod = prod * i

print("factorial of the number:", prod)

OUTPUT:

enter the number:6

factorial of the number: 720


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 7: Write a Python program to print Fibonacci series up to n limit.

OBJECTIVE: To print the Fibonacci series up to a given number ‘n’ using Python.

EXPLAINATION: The Fibonacci series is a sequence where each number is the sum of
the two

preceding ones, starting from 0 and 1. This program takes an integer input ‘n’ and prints
all

Fibonacci numbers less than or equal to ‘n’.

SOURCE CODE:

n=int(input("Enter the limit(n):"))

a,b =0,1

print("Fibonacci series up to",n,":")

while a<=n:

print(a,end=" ")

a,b =b,a+b

OUTPUT:

Enter the limit(n):20

Fibonacci series up to 20:

0 1 1 2 3 5 8 13
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 8: Write a program to check whether a number is prime or not.

OBJECTIVE: To check whether a given number is a prime number or not.

EXPLAINATION: A prime number is a number greater than 1 that has no divisors other
than 1

and itself.

SOURCE CODE:

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

if num>1:

for i in range(2,int(num**0.5)+1):

if num%i==0:

print(num,"is not prime")

else:

print(num,"is prime")

OUTPUT:

Enter a number:7

7 is prime
NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 9: Write a python program to reverse a number.

OBJECTIVE: To reverse a given number using a while loop.

EXPLAINATION: This program takes an integer as input and reverse its digits by
repeatedly

extracting the last digit using the modulus operator (%) and building the reverse number
step by

step using integer division (//).

SOURCE CODE:

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

rev=0

while num>0:

rev=(rev*10)+(num%10)

num=num//10

print("Reversed number is:",rev)

OUTPUT:

Enter a number:1234

Reversed number is: 4321


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 10: Write a python program to check whether a number is

palindrome or not.

OBJECTIVE: To check whether a given number is a palindrome or not.

EXPLAINATION: A palindrome number is one of that remains the same when its digits
are

reversed. This program reversed a given number using a while loop and compares it with
the

original number.

SOURCE CODE:

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

original=num

reverse=0

while num>0:

digit=num%10

reverse=reverse*10+digit

num=num//10

if original==reverse:

print("Palindrome number.")

else:

print("Not a palindrome.")

OUTPUT:

Enter a number:141

Palindrome number.
NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 11: Write a program to check whether a number is Armstrong or


not.

OBJECTIVE: To check whether a given number is an Armstrong number or not.

EXPLAINATION: An Armstrong number is a number that is equal to the sum of the cubes
of its

digits (for 3-digit numbers).

SOURCE CODE:

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

temp=num

sum=0

while num>0:

digit=num%10

sum+=digit**3

num//=10

if temp==sum:

print(temp,"is an Armstrong number.")

else:

print(temp,"is not an Armstrong number")

OUTPUT:

Enter a number:143

143 is not an Armstrong number

.
NAME: KRISHNA SINGH

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

DATE:17/11/2025

PROBLEM STATEMENT 12: Write a Python program to print the digit sum of a number.

OBJECTIVE: To find the sum of the digits of a given number.

EXPLAINATION: This program takes an integer as input and repeatedly extends each
digit

using the modulus (%) operators, adds them together, and removes the last digit using
integer

division (//).

SOURCE CODE:

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

original_num=num

sum_digit=0

while num > 0:

digit = num % 10

sum_digit += digit

num = num // 10

print(f"Sum of digits of {original_num}is: {sum_digit}")

OUTPUT:

Enter a number:12345

Sum of digits of 12345is: 15


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 13: Write a function to find whether a given number is prime or
not.

OBJECTIVE: To define a function that checks whether a given number is prime or not.

EXPLAINATION: A prime number is a number greater than 1 that has no divisors other
than 1

and itself. This program defines a function is prime(num) that returns whether a number
is prime

or not using a simple loop.

SOURCE CODE:

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

if num>1:

for i in range(2,int(num**0.5)+1):

if num%i==0:

print(num,"is not prime")

else:

print(num,"is prime")

OUTPUT:

Enter a number:8

8 is not prime
NAME KRISHNA SINGH

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

DATE:17/11/2025

PROBLEM STATEMENT 14: Write a recursive function to find the factorial of a number.

OBJECTIVE: To find the factorial of a given number using recursion.

EXPLAINATION: A factorial of a number n (written as n!) is the product of all positive


integer

up to n. In recursion, a function calls itself until a base condition is met -here, when n
becomes 1.

SOURCE CODE:

def fact(n):

if n == 0:

return 1

else:

return n * fact(n - 1)

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

print("The factorial of", num, "is:", fact(num))

OUTPUT:

Enter a number:5

The factorial of 5 is: 120


NAME: KRISHNA SINGH

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

DATE:17/11/2025

PROBLEM STATEMENT 15: Write a function that returns the sum of digits of a number
using

recursion.

OBJECTIVE: To find the sum of digits of a given number using recursion.

EXPLANIATION-This program defines a recursive function that breaks down the number
into

its digits. At each recursive call, it adds the last digit (n % 10) to the sum of the
remaining digits

(n // 10), until the number becomes 0.

SOURCE CODE-

def sum_digits(n):

if n==0:

return 0

return n % 10 + sum_digits(n // 10)

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

print("Sum of digits:", sum_digits(num))

OUTPUT:

Enter a number:1234

Sum of digits: 10
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 16- Write a Python program to find all prime numbers in a given

range using a function.

OBJECTIVE-To find and display all prime numbers within a given range using a function

DESCRIPTION- This program defines a function find_primes(start, end) that checks


each

number in the specified range to determine whether it is prime. A prime number is a


number

greater than 1 that has no divisors other than 1 and itself. The function returns a list of
all such

prime numbers.

SOURCE CODE-

def find_primes(start, end):

primes = []

for num in range(start, end + 1):

if num > 1:

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

break

else:

[Link](num)

return primes

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

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

prime_numbers = find_primes(start, end)


print(f"Prime numbers between {start} and {end} are: {prime_numbers}")

OUTPUT

Enter the start of the range: 10

Enter the end of the range: 50

Prime numbers between 10 and 50 are: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 17: Write a function to find the LCM and GCD of two numbers

without using built-in functions. Having short objective and description.

OBJECTIVE: To find the LCM (Least Common Multiple) and GCD (Greatest Common
Divisor)

Of two numbers without using built-in functions.

EXPLAINATION: This program defines two functions: - find_gcd (a ,b) finds the greatest
number that divides both a and b. - find_lcm (a, b) uses the relation LCM*GCD=a*b to
compute the least common multiple.

SOURCE CODE:

def find_gcd(a, b):

gcd = 1

i=1

while i<=a and i<=b:

if a %i==0 and b%i==0:

gcd = i

i+=1

return gcd
def find_lcm(a, b):

gcd = find_gcd(a,b)

lcm = (a * b) // gcd

return lcm

num1 = int(input("Enter first number:"))

num2 = int(input("Enter second number:"))

print("GCD of",num1, "and",num2,"is:",find_gcd(num1, num2))

print("LCM of",num1, "and",num2,"is:",find_lcm(num1, num2))

OUTPUT:

Enter first number:12

Enter second number:18

GCD of 12 and 18 is: 6

LCM of 12 and 18 is: 36


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT18: Write a program using a lambda function to calculate the


area of a

circle having short objective and description.

OBJECTIVE: To calculate the area of a circle using a lambda function.

EXPLAINATION: This program uses a lambda function to define a one-line formula for
finding

the area of a circle.

SOURCE CODE:

area=lambda r:3.14159*r*r

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

print("The area of the circle is:",area(radius))

OUTPUT:

Enter the radius of the circle:4

The area of the circle is: 50.26544


NAME: KRISHNA SINGH

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

DATE:17/11/2025

PROBLEM STATEMENT 19: Write a python program to count vowels and consonants in a

given string.

OBSERVATION: To count the number of vowels and consonants in a given string.

EXPLAINATION: This program takes a string input from the user and checks each
character. If

the character is an alphabet, it determines whether it’s a vowel(a, e, i, o, u) or a


consonant, and

counts them separately.

SOURCE CODE:

string = input("Enter a string:").lower()

vowels = 0

consonants = 0

for ch in string:

if [Link]():

if ch in 'aeiou':

vowels+= 1

else:

consonants+=1

print("Number of vowels:",vowels)

print("Number of consonants:",consonants)

OUTPUT:

Enter a string:Hello World

Number of vowels: 3

Number of consonants: 7
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 20: Write a program to check whether a string is palindrome or


not.

OBJECTIVE: To check whether a given string is a palindrome or not.

EXPLAINATION: A palindrome string is one that reads the same backward and forward.
This

program compares the original string with its reverse to determine if it’s a palindrome.

SOURCE CODE:

text =input("Enter a string:")

text =[Link]()

if text==text[::-1]:

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

OUTPUT:

Enter a string:hello

The string is not a palindrome.


NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 21: Write a python function to count the frequency of each
character

in a string.

OBJECTIVE: To count the frequency of each character in a given string using a function.

EXPLAINATION: This program defines a function that takes a string as input and uses a
loop to

count how many times each character appears. The results are stored in a dictionary,
where each

key is a character and its value is the count.

SOURCE CODE:

def char_frequency(text):

freq = {}

for ch in text:

if ch in freq:

freq[ch]+=1

else:

freq[ch]=1

return freq

string =input("Enter a string:")

print("Character frequencies:")

for key, value in char_frequency(string).items():

print(key,":",value)

OUTPUT:

Enter a string:hello
Character frequencies:

h:1

e:1

l:2

o:1

NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 22: Write a program to remove all punctuation marks and spaces
from

a string and check if it is palindrome.

OBJECTIVE: To remove punctuation marks and spaces from a string and check whether
it is a

palindrome.

EXPLIANATION: This program removes all punctuation and spaces using a loop and
string

filtering.

SOURCE CODE:

import string

text = input("Enter a string:")

cleaned =""

for ch in [Link]():

if ch not in [Link] and ch!="":

cleaned+=ch
if cleaned == cleaned[::-1]:

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

OUTPUT:

Enter a string:Hello World

The string is not a palindrome.


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 23: Write a program to find longest and shortest word in a
sentence.

OBJECTIVE: To find the longest and shortest words in a given sentence.

EXPLAINATION: This program takes a sentence as input, splits it into individual words,
and

then uses the min () and max () function to find the words with the smallest and largest
lengths.

SOURCE CODE:

sentence =input("Enter a sentence:")

words =[Link]()

longest =max(words,key=len)

shortest =min(words,key=len)

print("Longest word:",longest)

print("Shortest word:",shortest)

OUTPUT:

Enter a sentence:python makes programming easy

Longest word: programming

Shortest word: easy


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 24: Write a program to count the frequency of words in a


sentence.

The output should be displayed in a dictionary format where each unique word will be
the key

and its frequency will be the value of the dictionary.

OBJECTIVE: To count the frequency of each word in a sentence and display the result in
a

dictionary format.

EXPLAINATION: This program takes a sentence as input, splits it into words, and counts
how

many times each word appears.

Each unique word is used as a key, and its frequency is stored as the value in a
dictionary.

SOURCE CODE:

sentence = input("Enter a sentence: ")

words = [Link]().split()

freq = {}

for word in words:

if word in freq:

freq[word] += 1

else:

freq[word] = 1

print("Word frequency dictionary:")

print(freq)
OUTPUT:

Enter a sentence: Python is fun and Python is easy

Word frequency dictionary:

{'python': 2, 'is': 2, 'fun': 1, 'and': 1, 'easy': 1}

NAME: GOPAL RANA

DATE:17/11/2025

ROLL NO: 80

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 25: Write a Python program to create a list of numbers and print
their

sum and average.

OBJECTIVE: To create a list of numbers and calculate their sum and average.

EXPLAINATION: This program takes multiple numbers as input from the user, stores
them in a

list, and then uses the built-in sum() and len() functions to compute the total sum and
average of

the numbers.

SOURCE CODE:

numbers = list(map(float, input("Enter numbers separated by spaces: ").split()))

total = sum(numbers)

average = total / len(numbers)

print("List of numbers:", numbers)

print("Sum of numbers:", total)

print("Average of numbers:", average)

OUTPUT:

Enter numbers separated by spaces: 10 20 30 40 50

List of numbers: [10.0, 20.0, 30.0, 40.0, 50.0]

Sum of numbers: 150.0


Average of numbers: 30.0

NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 26: Write a program to find the largest and the smallest element
in a

list.

OBJECTIVE: To find the largest and smallest elements in a list.

EXPLAINATION: This program goes through each element in the list using a loop and

compares values to find the maximum and minimum manually

SOURCE CODE:

numbers = [12, 45, 7, 23, 56, 2, 99]

largest = numbers[0]

smallest = numbers[0]

for num in numbers:

if num > largest:

largest = num

if num < smallest:

smallest = num

print("List:", numbers)

print("Largest element:", largest)

print("Smallest element:", smallest)

OUTPUT:

List: [12, 45, 7, 23, 56, 2, 99]

Largest element: 99
Smallest element: 2

NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 27: Write a Python function to remove duplicates from a list
without

using set().

OBJECTIVE: Remove duplicate elements from a list while preserving order.

EXPLAINATION: This function iterates through the input list, adding each element to a
new list

only if it hasn't been added before.

SOURCE CODE:

def remove_duplicates(lst):

result = []

for item in lst:

if item not in result:

[Link](item)

return result

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

print(remove_duplicates(numbers))

OUTPUT:

[1, 2, 3, 4, 5]
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 28: Write a program to sort a list of tuples based on the second

element of each tuple.

OBJECTIVE: Sort a list of tuples based on the second element of each tuple.

EXPLAINATION: The program uses the 'sorted' function with a lambda key to sort tuples
by

their second value.

SOURCE CODE:

def sort_by_second_element(tuple_list):

return sorted(tuple_list, key=lambda x: x[1])

data = [(1, 3), (2, 1), (4, 2)]

sorted_data = sort_by_second_element(data)

print(sorted_data)

OUTPUT:

[(2, 1), (4, 2), (1, 3)]


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 29: Write a function that accepts a list of integers and returns a
new

list with only prime numbers.

OBJECTIVE: Extract prime numbers from a list of integers.

EXPLAINATION: The function checks each number in the input list and returns a new list

containing only prime numbers.

SOURCE CODE:

def is_prime(n):

if n < 2:

return False

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return False

return True

def filter_primes(lst):

return [num for num in lst if is_prime(num)]

numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]

prime_numbers = filter_primes(numbers)

print(prime_numbers)

OUTPUT:

[2, 3, 5, 7]
NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 30: Write a program to create and display a tuple containing
numbers

and string.

OBJECTIVE: Create a tuple containing numbers and strings, and display it.

EXPLAINATION: The program demonstrates how to define a tuple with mixed data types
and

print its contents.

SOURCE CODE:

my_tuple = (1, 2, 3, "apple", "banana", "cherry")

print("The tuple is:", my_tuple)

OUTPUT:

The tuple is: (1, 2, 3, 'apple', 'banana', 'cherry')


NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 31: Write a Python program to convert a list of tuples into

dictionary.

OBJECTIVE: Convert a list of tuples into a dictionary.

EXPLAINATION: Each tuple in the list contains a key-value pair, which is added to the

dictionary.

SOURCE CODE:

tuple_list = [("a", 1), ("b", 2), ("c", 3)]

dict_result = {}

for key, value in tuple_list:

dict_result[key] = value

print("The dictionary is:", dict_result)

OUTPUT:

The dictionary is: {'a': 1, 'b': 2, 'c': 3

}
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 32: Write a program to count the frequency of each character in
a

string using a dictionary.

OBJECTIVE: Count the frequency of each character in a string.

EXPLAINATION: The program iterates through the string and updates a dictionary with
the

number of occurrences of each character.

SOURCE CODE:

text = "hello world"

char_frequency = {}

for char in text:

if char in char_frequency:

char_frequency[char] += 1

else:

char_frequency[char] = 1

print("Character frequency:", char_frequency)

OUTPUT:

Character frequency: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 33: Write a Python program to find the most frequent element in
a

tuple.

OBJECTIVE: Find the element that appears most frequently in a tuple.

EXPLAINATION: The program iterates through the tuple and uses a dictionary to count
the

occurrences of each element. It then identifies the element with the highest frequency
and

displays it.

SOURCE CODE:

my_tuple = (1, 2, 3, 2, 4, 2, 5, 3, 1)

freq_dict = {}

for item in my_tuple:

if item in freq_dict:

freq_dict[item] += 1

else:

freq_dict[item] = 1

most_frequent = max(freq_dict, key=freq_dict.get)

print("The most frequent element is:", most_frequent)

OUTPUT:

The most frequent element is: 2


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 34: write a program to merge two dictionaries and sum values of

common keys.

OBJECTIVE: Merge two dictionaries, summing the values of keys that appear in both.

EXPLAINATION: The program iterates through both dictionaries. If a key exists in both, it
adds

their values; otherwise, it keeps the unique key-value pairs.

SOURCE CODE:

dict1 = {'a': 100, 'b': 200, 'c': 300}

dict2 = {'b': 150, 'c': 100, 'd': 250}

merged_dict = [Link]()

for key, value in [Link]():

if key in merged_dict:

merged_dict[key] += value

else:

merged_dict[key] += value

print("Merged dictionary:", merged_dict)

OUTPUT:

Merged dictionary: {'a': 100, 'b': 350, 'c': 400, 'd': 250}
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 35: Write a function to invert a dictionary, swap keys and values.

OBJECTIVE: Invert a dictionary so that its keys become values and its values become
keys.

EXPLAINATION: The function iterates through the original dictionary and creates a new

dictionary with keys and values swapped. Note: If the original dictionary has duplicate
values,

later keys will overwrite earlier ones.

SOURCE CODE:

def invert_dictionary(d):

inverted = {}

for key, value in [Link]():

inverted[value] = key

return inverted

original_dict = {'a': 1, 'b': 2, 'c': 3}

inverted_dict = invert_dictionary(original_dict)

print("Original dictionary:", original_dict)

print("Inverted dictionary:", inverted_dict)

OUTPUT:

Original dictionary: {'a': 1, 'b': 2, 'c': 3}

Inverted dictionary: {1: 'a', 2: 'b', 3: 'c'}


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 36: Write a Python program to demonstrate set creation and
basic set

operation union-intersection difference.

OBJECTIVE: Demonstrate how to create sets and perform basic set operations: union,

intersection, and difference.

EXPLAINATION: The program creates two sets and shows how to combine them (union),
find

common elements (intersection), and find elements present in one set but not the other

(difference).

SOURCE CODE:

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

union_set = set1 | set2

intersection_set = set1 & set2

difference_set = set1 - set2

print("Set 1:", set1)

print("Set 2:", set2)

print("Union:", union_set)

print("Intersection:", intersection_set)

print("Difference (set1 - set2):", difference_set)

OUTPUT:

Set 1: {1, 2, 3, 4, 5}

Set 2: {4, 5, 6, 7, 8}

Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}

Difference (set1 - set2): {1, 2, 3}


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 37: Write a Python program to read the content of a text file and

display it on the screen.

OBJECTIVE: Read the contents of a text file and display them on the screen.

EXPLAINATION: The program opens a text file in read mode, reads its content, and
prints it. It

automatically closes the file using a with statement.

SOURCE CODE:

file_path = '[Link]'

try:

with open(file_path, 'r') as file:

content = [Link]()

print("File content:\n")

print(content)

except FileNotFoundError:

print(f"Error: The file '{file_path}' does not exist.")

Example [Link] content:

Hello, this is a sample text file.

It contains multiple lines of text.

OUTPUT:

File content:

Hello, this is a sample text file.

It contains multiple lines of text.


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 38: Write a Python program to count the total number of lines in
a

file.

OBJECTIVE: Count the total number of lines present in a text file.

EXPLAINATION: The program opens a file in read mode and iterates through each line,

incrementing a counter to calculate the total number of lines.

SOURCE CODE:

file_path = '[Link]'

try:

with open(file_path, 'r') as file:

line_count = 0

for line in file:

line_count += 1

print(f"Total number of lines in the file: {line_count}")

except FileNotFoundError:

print(f"Error: The file '{file_path}' does not exist.")

Example [Link] content:

Hello, this is a sample text file.

It contains multiple lines of text.

Python makes file handling easy!

Output when program is run:

Total number of lines in the file: 3


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 39: Write a Python program to copy the content of one file to
another

file.

OBJECTIVE: Copy the content of a source file into a destination file.

DESCRIPTION: The program opens the source file in read mode and the destination file
in write

mode. It reads the content from the source and writes it to the destination file.

SOURCE CODE:

source_file = '[Link]'

destination_file = '[Link]'

try:

with open(source_file, 'r') as src:

content = [Link]()

with open(destination_file, 'w') as dest:

[Link](content)

print(f"Content from '{source_file}' has been copied to '{destination_file}'.")

except FileNotFoundError:

print(f"Error: The file '{source_file}' does not exist.")

Example [Link] content:

This is the original file.

It contains some text to be copied.

Python makes file handling easy!

Output when program is run:


Content from '[Link]' has been copied to '[Link]'.

OUTPUT

The [Link] file now contains:

This is the original file.

It contains some text to be copied.

Python makes file handling easy!


NAME :KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 40-Write a Python class, BankAccount with method, Deposit(),

Withdrawal(), and DisplayBalance().

OBJECTIVE: Create a simple BankAccount class to manage deposits, withdrawals, and


display

the current balance.

DESCRIPTION: The BankAccount class initializes with an account holder name and a
balance

(default 0). It provides methods to deposit money, withdraw money (with a check for
sufficient

balance), and display the current balance.

SOURCE CODE:

class BankAccount:

def __init__(self, owner, balance=0):

[Link] = owner

[Link] = balance

def deposit(self, amount):

if amount > 0:

[Link] += amount

print(f"{amount} deposited. New balance: {[Link]}")

else:

print("Deposit amount must be positive.")

def withdrawal(self, amount):

if amount > 0:

if amount <= [Link]:


[Link] -= amount

print(f"{amount} withdrawn. New balance: {[Link]}")

else:

print("Insufficient balance.")

else:

print("Withdrawal amount must be positive.")

def display_balance(self):

print(f"Account owner: {[Link]}, Balance: {[Link]}")

account = BankAccount("Alice", 1000)

account.display_balance()

[Link](500)

[Link](200)

account.display_balance()

Output:

Account owner: Alice, Balance: 1000

500 deposited. New balance: 1500

200 withdrawn. New balance: 1300

Account owner: Alice, Balance: 1300


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 41-Write a class student that stores name, roll number, and
marks of

three subjects and computes total and grade.

OBJECTIVE: Create a class to store student details, compute total marks, and
determine the

grade based on marks.

DESCRIPTION: The Student class stores a student’s name, roll number, and marks of
three

subjects. It has methods to calculate total marks and assign a grade based on the total
percentage.

SOURCE CODE:

class Student:

def __init__(self, name, roll_no, marks):

[Link] = name

self.roll_no = roll_no

[Link] = marks

def total_marks(self):

return sum([Link])

def grade(self):

total = self.total_marks()

percentage = total / 3

if percentage >= 90:

return 'A'

elif percentage >= 75:


return 'B'

elif percentage >= 60:

return 'C'

elif percentage >= 50:

return 'D'

else:

return 'F'

def display(self):

print(f"Name: {[Link]}")

print(f"Roll Number: {self.roll_no}")

print(f"Marks: {[Link]}")

print(f"Total: {self.total_marks()}")

print(f"Grade: {[Link]()}")

student1 = Student("John Doe", 101, [85, 78, 92])

[Link]()

OUTPUT:

Name: John Doe

Roll Number: 101

Marks: [85, 78, 92]

Total: 255

Grade: B
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 42-Write a class Rectangle that computes Area and Perimeter.

OBJECTIVE: Create a class to represent a rectangle and calculate its area and
perimeter.

DESCRIPTION: The Rectangle class stores the length and width of a rectangle. It
provides

methods to compute the area and perimeter.

SOURCE CODE:

class Rectangle:

def __init__(self, length, width):

[Link] = length

[Link] = width

def area(self):

return [Link] * [Link]

def perimeter(self):

return 2 * ([Link] + [Link])

def display(self):

print(f"Length: {[Link]}, Width: {[Link]}")

print(f"Area: {[Link]()}")

print(f"Perimeter: {[Link]()}")

rect = Rectangle(5, 3)

[Link]()

OUTPUT:

Length: 5, Width: 3

Area: 15
Perimeter: 16

NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 43-Write a simple tkinter program to create a window with the
label

Welcome to GUI Programming.

OBJECTIVE: Create a basic GUI window in Python using Tkinter with a welcoming label.

DESCRIPTION: The program uses the Tkinter library to create a window, adds a Label
widget

with a message, and runs the main event loop to display the window.

SOURCE CODE:

from tkinter import *

window = Tk()

[Link]("Simple GUI")

[Link]("400x200")

label = Label(window, text="Welcome to GUI Programming")

[Link](pady=50)

[Link]()

OUTPUT-

A GUI window appears with the title “Simple GUI” and a centered label displaying:

Welcome to GUI Programming


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 44-Write a GUI-based program to accept two numbers and


display

their sum.

OBJECTIVE: Create a GUI application to input two numbers and display their sum.

DESCRIPTION: The program uses Tkinter to create input fields for two numbers, a
button to

calculate the sum, and a label to display the result.

SOURCE CODE:

from tkinter import *

def calculate_sum():

try:

num1 = float([Link]())

num2 = float([Link]())

result = num1 + num2

label_result.config(text=f"Sum: {result}")

except ValueError:

label_result.config(text="Please enter valid numbers")

window = Tk()

[Link]("Sum Calculator")

[Link]("300x200")

Label(window, text="Enter first number:").pack(pady=5)

entry1 = Entry(window)

[Link](pady=5)
Label(window, text="Enter second number:").pack(pady=5)

entry2 = Entry(window)

[Link](pady=5)

Button(window, text="Calculate Sum", command=calculate_sum).pack(pady=10)

label_result = Label(window, text="Sum: ")

label_result.pack(pady=5)

[Link]()

OUTPUT:

A GUI window appears with:

• Two input fields to enter numbers

• A button labeled “Calculate Sum”

• A label showing the sum after clicking the button


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 45-Create a GUI application to change the background color of


the

window.

OBJECTIVE: Create a GUI application that allows the user to change the window’s
background

color.

DESCRIPTION: The program uses Tkinter to create buttons that, when clicked, change
the

background color of the main window.

SOURCE CODE:

from tkinter import *

def change_bg(color):

[Link](bg=color)

window = Tk()

[Link]("Background Color Changer")

[Link]("400x200")

Label(window, text="Click a button to change background color:", font=("Arial",

12)).pack(pady=10)

Button(window, text="Red", width=10, command=lambda:


change_bg("red")).pack(pady=5)

Button(window, text="Green", width=10, command=lambda:

change_bg("green")).pack(pady=5)

Button(window, text="Blue", width=10, command=lambda:


change_bg("blue")).pack(pady=5)
Button(window, text="Yellow", width=10, command=lambda:

change_bg("yellow")).pack(pady=5)

[Link]()

OUTPUT:

• A GUI window appears with an instruction label.

• Four buttons labeled Red, Green, Blue, Yellow.

• Clicking a button changes the window’s background color to the selected color.
NAME KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 46-Write a tkinter GUI application to take a name, input, and
display

a personalized greeting message.

OBJECTIVE: Create a GUI application that accepts a user’s name and displays a
personalized

greeting message.

DESCRIPTION: The program uses Tkinter to create an input field for the name, a button
to

submit, and a label to display the greeting message.

SOURCE CODE:

from tkinter import *

def greet():

name = entry_name.get()

if [Link]():

label_greeting.config(text=f"Hello, {name}! Welcome!")

else:

label_greeting.config(text="Please enter your name.")

window = Tk()

[Link]("Greeting App")

[Link]("400x200")

Label(window, text="Enter your name:", font=("Arial", 12)).pack(pady=10)

entry_name = Entry(window, font=("Arial", 12))

entry_name.pack(pady=5)

Button(window, text="Greet Me", font=("Arial", 12), command=greet).pack(pady=10)


label_greeting = Label(window, text="", font=("Arial", 14), fg="blue")

label_greeting.pack(pady=10)

[Link]()

OUTPUT:

• A GUI window appears with a label “Enter your name:”, an entry box, and a “Greet Me”

button.

• When the user enters their name (e.g., Alice) and clicks the button, the label updates:

Hello, Alice! Welcome!


NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 47-Create a GUI-based student marks calculator with input


fields for

three subjects and a button to calculate total and grade.

OBJECTIVE: Create a GUI application to input marks for three subjects and display the
total

marks and grade.

DESCRIPTION: The program uses Tkinter to create input fields for three subjects, a
button to

calculate the total and grade, and labels to display the results. The grade is assigned
based on

percentage:

• ≥ 90: A

• ≥ 75: B

• ≥ 60: C

• ≥ 50: D

• < 50: F

SOURCE CODE:

from tkinter import *

def calculate():

try:

marks1 = float([Link]())

marks2 = float([Link]())

marks3 = float([Link]())

total = marks1 + marks2 + marks3


percentage = total / 3

if percentage >= 90:

grade = 'A'

elif percentage >= 75:

grade = 'B'

elif percentage >= 60:

grade = 'C'

elif percentage >= 50:

grade = 'D'

else:

grade = 'F'

label_result.config(text=f"Total: {total}\nGrade: {grade}")

except ValueError:

label_result.config(text="Please enter valid numeric marks.")

window = Tk()

[Link]("Student Marks Calculator")

[Link]("400x350")

Label(window, text="Enter marks for Subject 1:", font=("Arial", 12)).pack(pady=5)

entry1 = Entry(window, font=("Arial", 12))

[Link](pady=5)

Label(window, text="Enter marks for Subject 2:", font=("Arial", 12)).pack(pady=5)

entry2 = Entry(window, font=("Arial", 12))

[Link](pady=5)

Label(window, text="Enter marks for Subject 3:", font=("Arial", 12)).pack(pady=5)

entry3 = Entry(window, font=("Arial", 12))

[Link](pady=5)

Button(window, text="Calculate", font=("Arial", 12),


command=calculate).pack(pady=15)
label_result = Label(window, text="", font=("Arial", 14), fg="green")

label_result.pack(pady=10)

[Link]()

OUTPUT

• Input Marks: 85, 78, 92

• Total: 255

• Grade: B
NAME: KRISHNA SINGH

DATE:17/11/2025

ROLL NO: 22

COURSE: BCA (AI & DS)

SECTION: B2

PROBLEM STATEMENT 48-Write a Tkinter GUI application to display an image and


provide

buttons to zoom in and out.

OBJECTIVE: Create a GUI application that displays an image and allows the user to
zoom in

and out using buttons.

DESCRIPTION: The program uses Tkinter along with PIL (Python Imaging Library) to load
and

display an image. Buttons are provided to increase or decrease the size of the image
dynamically

SOURCE CODE:

from tkinter import *

from PIL import Image, ImageTk

def zoom_in():

global img, tk_img, zoom

zoom *= 1.2

new_img = [Link]((int([Link] * zoom), int([Link] * zoom)))

tk_img = [Link](new_img)

[Link](image=tk_img)

def zoom_out():

global img, tk_img, zoom

zoom /= 1.2

new_img = [Link]((int([Link] * zoom), int([Link] * zoom)))

tk_img = [Link](new_img)
[Link](image=tk_img)

root = Tk()

[Link]("Image Zoom Example")

img = [Link]("your_image.jpg") # Change this to your image path

zoom = 1.0

tk_img = [Link](img)

label = Label(root, image=tk_img)

[Link]()

Button(root, text="Zoom In", command=zoom_in).pack(side=LEFT, padx=10, pady=10)

Button(root, text="Zoom Out", command=zoom_out).pack(side=LEFT, padx=10,


pady=10)

[Link]()

OUTPUT-

+---------------------------------------+

| [ Your Image Here ]

| |

+---------------------------------------+

| [ Zoom In ]

[ Zoom Out ]

+---------------------------------------+

You might also like