Practical File - CS
1. Write a Python program to input n marks, add them, and display the sum, average, maximum, and
minimum.
Source Code:
n = int(input("Enter the number of marks: "))
marks = [float(input(f"Enter mark {i + 1}: ")) for i in range(n)]
total = sum(marks)
average = total / n
maximum_mark = max(marks)
minimum_mark = min(marks)
print(f"Sum: {total}")
print(f"Average: {average:.2f}")
print(f"Maximum: {maximum_mark}")
print(f"Minimum: {minimum_mark}")
OUTPUT:
2. Write a Python program to input n decimal values, multiply all of them, and display the product
rounded to 3 decimal points.
Source Code:
from functools import reduce
n = int(input("Enter the number of decimal values: "))
decimals = [float(input(f"Enter decimal {i + 1}: ")) for i in range(n)]
product = reduce(lambda x, y: x * y, decimals)
rounded_product = round(product, 3)
print(f"Product: {rounded_product}")
OUTPUT:
3. Write a Python program to input n integers, add 100 to the odd ones while multiplying 3 to the
even ones. Display the final list in descending order.
Source Code:
n = int(input("Enter the number of integers: "))
integers = [int(input(f"Enter integer {i + 1}: ")) for i in range(n)]
result_list = [x + 100 if x % 2 != 0 else x * 3 for x in integers]
result_list.sort(reverse=True)
print("Final List (in descending order):", result_list)
OUTPUT:
4. Write a Python program to input n integers and get the smallest odd number from a list.
Source Code:
n = int(input("Enter the number of integers: "))
integers = [int(input(f"Enter integer {i + 1}: ")) for i in range(n)]
odd_numbers = [x for x in integers if x % 2 != 0]
if odd_numbers:
smallest_odd = min(odd_numbers)
print(f"The smallest odd number is: {smallest_odd}")
else:
print("No odd numbers in the list.")
OUTPUT:
5. Write a Python program to input n names of cities and display the number of cities whose length
is 4 or more.
Source Code:
n = int(input("Enter the number of cities: "))
cities = [input(f"Enter city {i + 1}: ") for i in range(n)]
filtered_cities = [city for city in cities if len(city) >= 4]
print(f"Number of cities with length 4 or more: {len(filtered_cities)}")
OUTPUT:
6. Write a Python program to input phone numbers in a list till the user wants and display the phone
numbers starting with 9.
Source Code:
phone_numbers = []
while True:
number = input("Enter a phone number (or 'stop' to finish): ")
if number.lower() == 'stop':
break
phone_numbers.append(number)
filtered_numbers = [num for num in phone_numbers if num.startswith('9')]
print("Phone numbers starting with 9:", filtered_numbers)
OUTPUT:
7. Write a Python program to input n integers and remove duplicates from a list.
Source Code:
n = int(input("Enter the number of integers: "))
integers = [int(input(f"Enter integer {i + 1}: ")) for i in range(n)]
unique_integers = list(set(integers))
print("List after removing duplicates:", unique_integers)
OUTPUT:
8. Write a Python program to input n integers and an upper value. All the values less than the upper
value should get removed from the list.
Source Code:
n = int(input("Enter the number of integers: "))
integers = [int(input(f"Enter integer {i + 1}: ")) for i in range(n)]
upper_value = int(input("Enter the upper value: "))
filtered_integers = [x for x in integers if x >= upper_value]
print("List after removing values less than the upper value:", filtered_integers)
OUTPUT:
9. Write a Python program to input a line of text and count the number of words in it.
Source Code:
text = input("Enter a line of text: ")
word_count = len(text.split())
print(f"Number of words in the text: {word_count}")
OUTPUT:
10. Write a Python program to input a line of text and shrink the number of spaces to one between
the words.
Source Code:
text = input("Enter a line of text: ")
shrunken_text = ' '.join(text.split())
print(f"Shrunken text: {shrunken_text}")
OUTPUT:
11. Write a Python program to input a line of text and count the number of words ending with a
vowel in it.
Source Code:
text = input("Enter a line of text: ")
words = text.split()
vowel_endings = [word for word in words if word[-1].lower() in 'aeiou']
print(f"Number of words ending with a vowel: {len(vowel_endings)}")
OUTPUT:
12. Write a Python program to input a line of text and count the number of words that are
palindrome in it.
Source Code:
text = input("Enter a line of text: ")
words = text.split()
palindrome_count = sum(word == word[::-1] for word in words)
print(f"Number of palindrome words: {palindrome_count}")
OUTPUT:
13. Write a Python program to input a m*n matrix and display it.
Source Code:
m = int(input("Enter the number of rows: "))
n = int(input("Enter the number of columns: "))
matrix = [[int(input(f"Enter element at ({i + 1}, {j + 1}): ")) for j in range(n)] for i in range(m)]
print("Matrix:")
for row in matrix:
print(row)
OUTPUT:
14. Write a Python program to input a m*n matrix and display the sum of all odd and even values.
Source Code:
m = int(input("Enter the number of rows: "))
n = int(input("Enter the number of columns: "))
matrix = [[int(input(f"Enter element at ({i + 1}, {j + 1}): ")) for j in range(n)] for i in range(m)]
sum_odd = sum(matrix[i][j] for i in range(m) for j in range(n) if matrix[i][j] % 2 != 0)
sum_even = sum(matrix[i][j] for i in range(m) for j in range(n) if matrix[i][j] % 2 == 0)
print(f"Sum of odd values: {sum_odd}")
print(f"Sum of even values: {sum_even}")
OUTPUT:
15. Write a Python program to input a m*n square matrix and find the sum of all the diagonal
elements.
Source Code:
n = int(input("Enter the size of the square matrix: "))
matrix = [[int(input(f"Enter element at ({i + 1}, {j + 1}): ")) for j in range(n)] for i in range(n)]
diagonal_sum = sum(matrix[i][i] for i in range(n))
print(f"Sum of diagonal elements: {diagonal_sum}")
OUTPUT:
16. Write a Python program to input a m*n matrix and find the row sums and col sums.
Source Code:
m = int(input("Enter the number of rows: "))
n = int(input("Enter the number of columns: "))
matrix = [[int(input(f"Enter element at ({i + 1}, {j + 1}): ")) for j in range(n)] for i in range(m)]
row_sums = [sum(row) for row in matrix]
col_sums = [sum(matrix[i][j] for i in range(m)) for j in range(n)]
print("Row sums:", row_sums)
print("Column sums:", col_sums)
OUTPUT:
17. Write a Python program to input n students’ roll numbers and names, search for a name given a
roll number.
Source Code:
n = int(input("Enter the number of students: "))
students = {}
for _ in range(n):
roll_number = input("Enter student's roll number: ")
name = input("Enter student's name: ")
students[roll_number] = name
search_roll = input("Enter roll number to search: ")
if search_roll in students:
print(f"Name
OUTPUT:
18. Write a Python program to input n doctors’ names, fees, and gender. Display the number of male
doctors with fees greater than 1000, also the number of female doctors with fees less than 800.
Source Code:
n = int(input("Enter the number of doctors: "))
doctors = []
for _ in range(n):
name = input("Enter doctor's name: ")
fees = float(input("Enter doctor's fees: "))
gender = input("Enter doctor's gender (M/F): ").upper()
doctors.append((name, fees, gender))
male_doctors_greater_than_1000 = sum(1 for _, fees, gender in doctors if gender == 'M' and fees >
1000)
female_doctors_less_than_800 = sum(1 for _, fees, gender in doctors if gender == 'F' and fees < 800)
print(f"Number of male doctors with fees greater than 1000: {male_doctors_greater_than_1000}")
print(f"Number of female doctors with fees less than 800: {female_doctors_less_than_800}")
OUTPUT:
19. Write a Python program to find the second smallest number in a list.
Source Code:
n = int(input("Enter the number of elements in the list: "))
numbers = [int(input(f"Enter element {i + 1}: ")) for i in range(n)]
unique_numbers = list(set(numbers)) # Removing duplicates
unique_numbers.sort()
if len(unique_numbers) >= 2:
second_smallest = unique_numbers[1]
print(f"The second smallest number is: {second_smallest}")
else:
print("List does not have a second smallest number.")
OUTPUT:
20. Write a Python program to input a string and find the frequency of the characters in it.
Source Code:
string = input("Enter a string: ")
character_frequency = {}
for char in string:
if char in character_frequency:
character_frequency[char] += 1
else:
character_frequency[char] = 1
print("Character frequencies:")
for char, frequency in character_frequency.items():
print(f"{char}: {frequency}")
OUTPUT:
21. Write a Python program to input n marks, add them, and display the sum and average.
Source Code:
n = int(input("Enter the number of marks: "))
marks = tuple(float(input(f"Enter mark {i + 1}: ")) for i in range(n))
total = sum(marks)
average = total / n
print(f"Sum: {total}")
print(f"Average: {average:.2f}")
OUTPUT:
22. Write a Python program to input n integers, and find the number of odd and even integers.
Source Code:
n = int(input("Enter the number of integers: "))
integers = tuple(int(input(f"Enter integer {i + 1}: ")) for i in range(n))
odd_count = sum(1 for num in integers if num % 2 != 0)
even_count = sum(1 for num in integers if num % 2 == 0)
print(f"Number of odd integers: {odd_count}")
print(f"Number of even integers: {even_count}")
OUTPUT:
23. Write a Python program to input n integers, add them, then display the 2nd half followed by the
first half of integers each separated by "@".
Source Code:
n = int(input("Enter the number of integers: "))
integers = tuple(int(input(f"Enter integer {i + 1}: ")) for i in range(n))
total = sum(integers)
second_half = integers[n // 2:]
first_half = integers[:n // 2]
result = second_half + first_half
print("Result:", "@".join(map(str, result)))
OUTPUT:
24. Write a Python program to declare a tuple with 10 integers. Display the count of a value entered
by the user.
Source Code:
numbers = (10, 5, 8, 10, 2, 7, 10, 3, 6, 10)
value_to_count = int(input("Enter a value to count: "))
count = numbers.count(value_to_count)
print(f"Count of {value_to_count}: {count}")
OUTPUT:
25. Write a Python program to input n names and display the names (reversed) in the opposite input
order.
Source Code:
n = int(input("Enter the number of names: "))
names = tuple(input(f"Enter name {i + 1}: ")[::-1] for i in range(n))
print("Reversed Names in Opposite Order:")
for name in reversed(names):
print(name)
OUTPUT:
26. Write a Python program to create a telephone database to store n records of phone numbers
and names. Input a phone number to display the corresponding name.
Source Code:
n = int(input("Enter the number of records: "))
telephone_database = {}
# Input phone numbers and names
for _ in range(n):
name = input("Enter name: ")
phone_number = input("Enter phone number: ")
telephone_database[phone_number] = name
# Input a phone number to display the corresponding name
search_number = input("Enter phone number to search: ")
if search_number in telephone_database:
print(f"Name for phone number {search_number}: {telephone_database[search_number]}")
else:
print(f"No record found for phone number {search_number}")
OUTPUT:
27. Write a Python program to input roll numbers, names, and marks of 3 subjects of n students and
display a performance report.
Source Code:
n = int(input("Enter the number of students: "))
students = {}
# Input roll numbers, names, and marks
for _ in range(n):
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
marks = [float(input(f"Enter marks for subject {i + 1}: ")) for i in range(3)]
average = sum(marks) / 3
if average >= 80:
grade = 'A'
elif 60 <= average < 80:
grade = 'B'
elif 40 <= average < 60:
grade = 'C'
else:
grade = 'FAIL'
students[roll_number] = {'name': name, 'average': average, 'grade': grade}
# Display performance report
print("\nPerformance Report:")
for roll_number, data in students.items():
print(f"Roll Number: {roll_number}, Name: {data['name']}, Average: {data['average']:.2f}, Grade:
{data['grade']}")
OUTPUT:
28. Write a Python program to input a line of text and find the frequency of the characters in it.
Source code:
text = input("Enter a line of text: ")
character_frequency = {}
for char in text:
if char in character_frequency:
character_frequency[char] += 1
else:
character_frequency[char] = 1
print("Character frequencies:")
for char, frequency in character_frequency.items():
print(f"{char}: {frequency}")
OUTPUT:
29. Write a Python program to input a line of text and find the number of capital and small alphabets
in it.
Source code:
text = input("Enter a line of text: ")
alphabet_count = {'capital': 0, 'small': 0}
for char in text:
if char.isalpha():
if char.isupper():
alphabet_count['capital'] += 1
else:
alphabet_count['small'] += 1
print("Alphabet counts:")
print(f"Capital: {alphabet_count['capital']}")
print(f"Small: {alphabet_count['small']}")
OUTPUT:
30. Write a Python program to the names and total marks of two different classes in two different
dictionaries. Display the topper names along with classes.
Source code:
class_1 = {}
class_2 = {}
# Input names and total marks for class 1
n1 = int(input("Enter the number of students in class 1: "))
for _ in range(n1):
name = input("Enter name: ")
total_marks = float(input("Enter total marks: "))
class_1[name] = total_marks
# Input names and total marks for class 2
n2 = int(input("Enter the number of students in class 2: "))
for _ in range(n2):
name = input("Enter name: ")
total_marks = float(input("Enter total marks: "))
class_2[name] = total_marks
# Find the topper names
topper_class_1 = max(class_1, key=class_1.get)
topper_class_2 = max(class_2, key=class_2.get)
print("Topper in Class 1:", topper_class_1)
print("Topper in Class 2:", topper_class_2)
OUTPUT:
31. Write a Python program for political parties along with the number of members and party
president name. Display the party names with the maximum and minimum party members.
Source code:
n = int(input("Enter the number of political parties: "))
parties = {}
# Input party details
for _ in range(n):
party_name = input("Enter party name: ")
members = int(input("Enter number of members: "))
president_name = input("Enter party president name: ")
parties[party_name] = {'members': members, 'president': president_name}
# Find the party names with the maximum and minimum members
max_members_party = max(parties, key=lambda x: parties[x]['members'])
min_members_party = min(parties, key=lambda x: parties[x]['members'])
print("Party with maximum members:", max_members_party)
print("Party with minimum members:", min_members_party)
OUTPUT:
32. Write a Python program to input n grocery items with item id, name, price, and quantity. Update
the price for a given item id.
Source Code:
n = int(input("Enter the number of grocery items: "))
grocery_items = {}
# Input grocery item details
for _ in range(n):
item_id = input("Enter item id: ")
name = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter item quantity: "))
grocery_items[item_id] = {'name': name, 'price': price, 'quantity': quantity}
# Update price for a given item id
update_id = input("Enter item id to update price: ")
if update_id in grocery_items:
new_price = float(input("Enter new price: "))
grocery_items[update_id]['price'] = new_price
print(f"Price updated for {grocery_items[update_id]['name']} (ID: {update_id})")
else:
print(f"No item found with ID {update_id}")
# Display updated grocery items
print("\nUpdated Grocery Items:")
for item_id, details in grocery_items.items():
print(f"ID: {item_id}, Name: {details['name']}, Price: {details['price']}, Quantity:
{details['quantity']}")
OUTPUT:
33. Write a Python menu-driven program to create a set of n country-capital pairs and then search a
capital for a given country and vice versa.
Source Code:
n = int(input("Enter the number of country-capital pairs: "))
countries_capitals = {}
# Input country-capital pairs
for _ in range(n):
country = input("Enter country: ")
capital = input("Enter capital: ")
countries_capitals[country] = capital
# Menu-driven search
while True:
print("\n1. Search capital for a country")
print("2. Search country for a capital")
print("3. Exit")
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
search_country = input("Enter country to search for capital: ")
if search_country in countries_capitals:
print(f"Capital for {search_country}: {countries_capitals[search_country]}")
else:
print(f"No capital found for {search_country}")
elif choice == 2:
search_capital = input("Enter capital to search for country: ")
found_countries = [country for country, capital in countries_capitals.items() if capital ==
search_capital]
if found_countries:
print(f"Countries with capital {search_capital}: {', '.join(found_countries)}")
else:
print(f"No country found with capital {search_capital}")
elif choice == 3:
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")
OUTPUT:
34. Write a Python program to input 20 question numbers in integers along with the questions. Ask a
question randomly.
Source Code:
import random
questions = {}
# Input questions
for i in range(20):
question_number = int(input(f"Enter question number {i + 1}: "))
question = input(f"Enter question for number {i + 1}: ")
questions[question_number] = question
# Ask a question randomly
random_question_number = random.choice(list(questions.keys()))
print(f"Randomly selected question (Number {random_question_number}):
{questions[random_question_number]}")
OUTPUT:
35. Write a Python program to input 20 question numbers in integers along with the questions and 4
options along with the correct option. Ask 5 questions randomly (without repetition), add 5 for a
correct answer while deduct 2 for an incorrect attempt. Finally, display the total score achieved.
Source Code:
import random
questions = {}
# Input questions with options and correct answers
for i in range(20):
question_number = int(input(f"Enter question number {i + 1}: "))
question = input(f"Enter question for number {i + 1}: ")
options = [input(f"Enter option {j + 1}: ") for j in range(4)]
correct_option = int(input(f"Enter correct option number (1-4) for question {i + 1}: "))
questions[question_number] = {'question': question, 'options': options, 'correct_option':
correct_option}
# Ask 5 questions randomly
selected_questions = random.sample(list(questions.keys()), 5)
# Evaluate and display the total score achieved
total_score = 0
for question_number in selected_questions:
print(f"\nQuestion {question_number}: {questions[question_number]['question']}")
for i, option in enumerate(questions[question_number]['options']):
print(f"{i + 1}. {option}")
user_answer = int(input("Enter your answer (1-4): "))
if user_answer == questions[question_number]['correct_option']:
total_score += 5
print("Correct! +5 points")
else:
total_score -= 2
print(f"Incorrect! -2 points. Correct option was
{questions[question_number]['correct_option']}")
print(f"\nTotal Score Achieved: {total_score}")
OUTPUT: