0% found this document useful (0 votes)
28 views20 pages

Harjot 19 - 34 Python

Uploaded by

baadshahyash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views20 pages

Harjot 19 - 34 Python

Uploaded by

baadshahyash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Harjot Singh 09121102023 BCA III E2

Practical No 19
AIM: Write a program to print the following pattern:
*
**
***
****
*****
****
***
**
*
Solution:
def print_pattern(n):

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


print('*' * i)
for i in range(n - 1, 0, -1):
print('*' * i)
print_pattern(5)

Output:
Harjot Singh 09121102023 BCA III E2

Practical NO 20
AIM: Write a program to enter a five-digit number and then display the number in the following
format (just an example):
12345 1
2345 12
345 123
45 1234
5 12345
Solution:
num = 12345
num_str = str(num)
for i in range(5):
left_part = num_str[i:]
print(' ' * i + left_part)
num = 12345
num_str = str(num)
FOR SECOND :
for i in range(1, 6):
right_part = ''.join(str(j) for j in range(1, i + 1))

print(right_part)

Output:
Harjot Singh 09121102023 BCA III E2

Practical NO 21
AIM: Write a program to check if the list contains a palindrome of elements, use copy method.
Solution:
elements = ["madam", "racecar", "hello", "world"]
elements_copy = elements.copy()
palindromes = []
for item in elements_copy:
if item == item[::-1]:
palindromes.append(item)
if palindromes:
print("The list contains palindromes:", ', '.join(palindromes))
else:
print("The list does not contain a palindrome.")
Output:

Practical NO 22
Harjot Singh 09121102023 BCA III E2

AIM: Write a program to print the following pattern using nested loop :
*
**
***
****
*****

Solution:
rows = 5

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


for j in range(i):
print('*', end='')
print()
Output:

Practical NO 23
Harjot Singh 09121102023 BCA III E2

AIM: Write a program that has nested list to store topper details. Edit the details and reprint the
details. Make it a menu driven program.
Solution:

topper_details = [
["Alice", "Mathematics", 95],
["Bob", "Physics", 90],
["Charlie", "Chemistry", 92]
]

while True:
print("\nMenu:\n1. Display Topper Details\n2. Edit Topper Details\n3. Exit")
choice = input("Enter your choice: ")

if choice == '1':
print("\nTopper Details:\nName\tSubject\tScore")
for name, subject, score in topper_details:
print(f"{name}\t{subject}\t{score}")

elif choice == '2':


name = input("Enter the name of the topper to edit: ")
for details in topper_details:
if details[0].lower() == name.lower():
new_subject = input(f"Current Subject: {details[1]}. Enter new subject (or press Enter
to keep current): ")
new_score = input(f"Current Score: {details[2]}. Enter new score (or press Enter to
keep current): ")

details[1] = new_subject if new_subject else details[1]


details[2] = int(new_score) if new_score else details[2]
Harjot Singh 09121102023 BCA III E2

print("Details updated successfully!")


break
else:
print("Topper not found.")

elif choice == '3':


print("Exiting the program.")
break

else:
print("Invalid choice! Please try again.")
Output:

Practical NO 24
Harjot Singh 09121102023 BCA III E2

AIM: WAP to create three tuples namely employee name, salary, designation. Insert at least 5
records and perform the following operations:
1. Zip the tuples
2. Extract the names of employees who are designer and create a new tuple containing these
names
3. Sort the tuples based on salary
4. Rename the position developer with quality engineer
5. Add a new position quality analyst with salary 75000
Solution:
employee_name = (“Ayush”, “Jayanshu”, “Kaushika”, “Vanshika”, “Tanya”, “Harjot”, “Navya”)
designation = (“CEO”, “Butler”, “Manager”, “Developer”, “Designer”, “Developer”,
“Designer”)
salary = (1000000, 12000, 15000, 20000, 26000, 15000, 22000)
zipped_data = list(zip(employee_name,designation,salary))
print(“Zipped Data:”)
for employee in zipped_data:
print(employee)
designer_names = tuple([name for name, _, designation in zipped_data if designation ==
“Designer”])
print(“\nDesigner Names:”)
print(designer_names)
sorted_data = sorted(zipped_data, key=lambda x: x[2])
print(“\nSorted Data by Salary:”)
for employee in sorted_data:
print(employee)
updated_data = [(name, salary, “Quality Engineer” if designation == "Developer" else
designation) for name, salary, designation in zipped_data]
print("\nUpdated Data:")
for employee in updated_data:
print(employee)
new_employee = ("Rahul", 75000, "Quality Analyst")
updated_data.append(new_employee)
Harjot Singh 09121102023 BCA III E2

print("\nUpdated Data with New Employee:")


for employee in updated_data:
print(employee)
Output:

Practical NO 25
Harjot Singh 09121102023 BCA III E2

Aim: Create two lists, name and marks of 5 student and perform the following operations:
1. Display both the list
2. Append the list 2 with list 1.
3. Display the name and marks of student at index 2.
4. Add the name and marks of two students.
5. Insert a student record at index 3.
6. Copy both the lists to a new list.
7. Copy the items of name list from index 1:4 into a new list.
8. Remove the student record of a particular student.
9. Remove the student record at index 4.
10. Remove the next item.
11. Remove the first item of marks list.
12. Delete all the records of list marks.
13. Delete the list name.
Solution:
name = ["John", "Emma", "Michael", "Sophia", "William"]
marks = [85, 90, 78, 92, 88]
print("Student Names:", name)
print("Student Marks:", marks)
student_records = list(zip(name, marks))
print("Student Records:", student_records)
print("Student at Index 2:", student_records[2])
new_students = [("Olivia", 95), ("James", 89)]
student_records.extend(new_students)
print("Updated Student Records:", student_records)
student_records.insert(3, ("Isabella", 91))
print("Updated Student Records after Insertion:", student_records)
copied_records = student_records.copy()
print("Copied Student Records:", copied_records)
sliced_records = student_records[1:5]
print("Sliced Student Records:", sliced_records)
del student_records[4]
print("Updated Student Records after Deletion:", student_records)
Harjot Singh 09121102023 BCA III E2

del marks[0]
print("Updated Marks List:", marks)
del marks[:]
print("Marks List after Deletion:", marks)
del name
print("Name List after Deletion:", locals().get('name'))

Output:

Practical NO: 26
Harjot Singh 09121102023 BCA III E2

Aim: Write a program that creates a dictionary of radius of a circle and its circumference.
Solution:
radius=int(input("Enter the radius of a circle: "))
circumference=2*3.14*radius
circle={"radius":radius,
"circumference:":circumference}
print(“Circle: ”,circle)

Output:

Practical NO 27
Harjot Singh 09121102023 BCA III E2

AIM: Write a program to store a sparse matrix as dictionary.


Solution:
matrix=[[0,0,0],[1,0,3],[0,1,0]]
dict={"matrix":matrix}
print(dict)

Output:

Practical No 28
Harjot Singh 09121102023 BCA III E2

Aim: Write a program in python to add a dictionary of five states and their code for eg delhi dl and
perform the following

1. Add 5 more states to previous dictionary


2. Take input from user to find a code for respective state
3. If state exist, code is printed.
4. Set a default value “Sorry no idea”.

Solution:

States={"Delhi":"DL", "Rajasthan":"RJ","Punjab":"PB","Uttrakhand":"UK"}

print(States)

States.update({"Gujarat":"GJ","Madhay Pradesh":"MP"})

print(States)

search=input("Enter the state code:");

if search in States:

print(f"The code for {search} is {States[search]}")

else:

print("Sorry no idea")

Output:

Practical No 29
Harjot Singh 09121102023 BCA III E2

Aim: Create a dictionary tools keys are month name and values are number of days in the
corresponding month

1. Ask user to enter month name and use dictionary to tell them how many days are in the month
2. Print all the keys in alphabetically order
3. Print all the month with 31 days
4. Print the key value pair sorted by number of days in each month

Solution:

months = {

"Jan": 31, "Feb": 28, "March": 31, "April": 30, "May": 31,

"June": 30, "July": 31, "Aug": 31, "Sep": 30, "Oct": 31,

"Nov": 30, "Dec": 31

sort_months = sorted(months.keys())

for month in sort_months:

days = months[month]

print(f"{month}: {days} days")

print("\n")

user_input = input("Enter month: ")

if user_input in months:

days = months[user_input]

print(f"{user_input} has {days} days")

else:

print("Invalid month")

print("\nMonths with 31 days:")

for month, days in months.items():

if days == 31:

print(month)

Output:
Harjot Singh 09121102023 BCA III E2

Practical No 30
Harjot Singh 09121102023 BCA III E2

Aim: Write a program to find intersection, union symmetric difference between two sets.
Solution:
def set_operations(set1, set2):

union_set = set1.union(set2)

intersection_set = set1.intersection(set2)

sym_diff_set = set1.symmetric_difference(set2)

print(f"Union: {union_set}")

print(f"Intersection: {intersection_set}")

print(f"Symmetric Difference: {sym_diff_set}")

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

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

set_operations(set1, set2)

Output:

Practical No 31
Harjot Singh 09121102023 BCA III E2

Aim: Write a program that creates two sets one of even number in range 1-10 and the other has all
composite numbers in range 1-20. Demonstrate the use all() function, issuperset() function, len function
and sum function on the sets.

Solution:
even_numbers = {x for x in range(1, 11) if x % 2 == 0}

composite_numbers = {x for x in range(2, 21) if any(x % i == 0 for i in range(2, x))}

print("Even Numbers (1-10):", even_numbers)

print("Composite Numbers (1-20):", composite_numbers)

print("Are all numbers in 'even_numbers' greater than 0?", all(num > 0 for num in even_numbers))

print("Is 'composite_numbers' a superset of 'even_numbers'?",


composite_numbers.issuperset(even_numbers))

print("Length of 'even_numbers':", len(even_numbers))

print("Length of 'composite_numbers':", len(composite_numbers))

print("Sum of 'even_numbers':", sum(even_numbers))

print("Sum of 'composite_numbers':", sum(composite_numbers))

Output:

Practical No 32
Harjot Singh 09121102023 BCA III E2

Aim: Wap to add two integer using function


Solution:
a=int(input("Enter value of a:"))

b=int(input("Enter value of b:"))

def sum(a,b):

sum=a+b

return sum

print("Sum is:")

print(sum(a,b))

Practical No33
Harjot Singh 09121102023 BCA III E2

Aim: Wap to implement local and global variable.


Solution:

a=int(input("Enter value of a:"))

b=int(input("Enter value of b:"))

def funct(a,b):

sum=a+b

c=a-b

return sum

print("Sum is:",sum)

print("declared variable is :",c)

Output:

We have declared c as local scope.

Practical No 34
Harjot Singh 09121102023 BCA III E2

Aim: Wap to demonstrate excess of variable in inner and outer function.


Solution:

def outer_function():

outer_var = "I am from outer function"

def inner_function():

print(outer_var)

inner_var = "I am from inner function"

print(inner_var)

inner_function()

print(outer_var)

outer_function()

Output:

You might also like