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

Practical CS

The document contains source code for several Python programs that perform various string and list/dictionary manipulations. Program 1 checks if a string is a palindrome. Program 2 counts the numbers of uppercase, lowercase, vowels and consonants in a string. Program 3 implements a menu-driven program to convert case of characters in a string to uppercase, lowercase, title case, swap case and sentence case. Program 4 implements a basic calculator using functions for addition, subtraction, multiplication and division.
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)
52 views22 pages

Practical CS

The document contains source code for several Python programs that perform various string and list/dictionary manipulations. Program 1 checks if a string is a palindrome. Program 2 counts the numbers of uppercase, lowercase, vowels and consonants in a string. Program 3 implements a menu-driven program to convert case of characters in a string to uppercase, lowercase, title case, swap case and sentence case. Program 4 implements a basic calculator using functions for addition, subtraction, multiplication and division.
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/ 22

PRACTICAL -16

Ques : Write a Program Checking a string for Palindrome


Source Code:
a = input("enter string : ")

for i in range(0,(len(a))//2):
if a[i]==a[len(a)-i-1]:
b=1
else:
b=2
if b==1:
print("palindrome")
else:
print(" not pallindrome :(")

Output :
PRACTICAL – 17
Ques : Write a Program to Count uppercase, lowercase, vowels, consonants
in a string
Source Code:
string = input("ENTER A STRING : ")

upper_count = 0
lower_count = 0
vowel_count = 0
consonant_count = 0

for char in string:


if char >= 'A' and char <= 'Z':
upper_count += 1

elif char >= 'a' and char <= 'z':


lower_count += 1

if char in "aeiouAEIOU":
vowel_count += 1
if char not in "aeiouAEIOU ":
consonant_count += 1

print("Uppercase letters:", upper_count)


print("Lowercase letters:", lower_count)
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)

Output :
PRACTICAL – 18
Ques : Write a Program to Menu driven program to convert the case of
characters in a string - UPPERCASE, lowercase, Title Case, sWAP cASE,
Sentence Case
Source Code:
def convert_to_uppercase(string):
result = ""
for char in string:
if 'a' <= char <= 'z':
char = chr(ord(char) - 32)
result += char
return result

def convert_to_lowercase(string):
result = ""
for char in string:
if 'A' <= char <= 'Z':
char = chr(ord(char) + 32)
result += char
return result

def convert_to_title_case(string):
result = ""
is_space = True
for char in string:
if is_space:
if 'a' <= char <= 'z':
char = chr(ord(char) - 32)
else:
if 'A' <= char <= 'Z':
char = chr(ord(char) + 32)
result += char
if char == ' ':
is_space = True
else:
is_space = False
return result

def convert_to_swap_case(string):
result = ""
for char in string:
if 'a' <= char <= 'z':
char = chr(ord(char) - 32)
elif 'A' <= char <= 'Z':
char = chr(ord(char) + 32)
result += char
return result

def convert_to_sentence_case(string):
result = ""
is_sentence_end = True
for char in string:
if is_sentence_end:
if 'a' <= char <= 'z':
char = chr(ord(char) - 32)
else:
if 'A' <= char <= 'Z':
char = chr(ord(char) + 32)
result += char
if char in ['.', '!', '?']:
is_sentence_end = True
else:
is_sentence_end = False
return result

def menu():
print("Menu:")
print("1. Convert to UPPERCASE")
print("2. Convert to lowercase")
print("3. Convert to Title Case")
print("4. Convert to sWAP cASE")
print("5. Convert to Sentence Case")
choice = input("Enter your choice: ")

if choice == '1':
string = input("Enter a string: ")
print("Result:", convert_to_uppercase(string))
elif choice == '2':
string = input("Enter a string: ")
print("Result:", convert_to_lowercase(string))
elif choice == '3':
string = input("Enter a string: ")
print("Result:", convert_to_title_case(string))
elif choice == '4':
string = input("Enter a string: ")
print("Result:", convert_to_swap_case(string))
elif choice == '5':
string = input("Enter a string: ")
print("Result:", convert_to_sentence_case(string))
else:
print("Invalid choice. Please try again.")

menu()
Output :
PRACTICAL – 19
Ques : Write a Program to Menu driven program to convert the case of
characters in a string - UPPERCASE, lowercase, Title Case, sWAP cASE,
Sentence Case
Source Code:
def add(num1, num2):
return num1 + num2

def subtract(num1, num2):


return num1 - num2

def multiply(num1, num2):


return num1 * num2

def divide(num1, num2):


if num2 != 0:
return num1 / num2
else:
return "Error: Division by zero is not allowed."

def calculator():
print("Welcome to the calculator!")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

while True:
choice = input("Enter your choice (1-5): ")

if choice == '1':
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = add(num1, num2)
print("Result: ", result)

elif choice == '2':


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = subtract(num1, num2)
print("Result: ", result)

elif choice == '3':


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = multiply(num1, num2)
print("Result: ", result)

elif choice == '4':


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = divide(num1, num2)
print("Result: ", result)

elif choice == '5':


print("Exiting...")
break

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

calculator()
Output :
PRACTICAL – 20
Ques : Write a Program to Find the largest/smallest number in a list/tuple
Source Code:
def find_largest_number(numbers):
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
def find_smallest_number(numbers):
smallest = numbers[0]
for num in numbers:
if num < smallest:
smallest = num
return smallest

numbers = eval(input("enter list or tuple"))


largest_number = find_largest_number(numbers)
print("The largest number is:", largest_number)
smallest_number = find_smallest_number(numbers)
print("The smallest number is:", smallest_number)

Output :
PRACTICAL -21

Ques. Input a list of numbers and swap elements at the even location with
the elements at the odd location.
Source Code
def swap_elements(input_list):
for i in range(0, len(input_list)-1, 2):
input_list[i], input_list[i+1] = input_list[i+1], input_list[i]
def main():
numbers = list(map(int, input("Enter a list of numbers separated by
space: ").split()))
if len(numbers) % 2 == 0:
swap_elements(numbers)
print("List after swapping elements at even and odd locations:",
numbers)
else:
print("Number of elements in the list should be even for
swapping.")
if __name__ == "__main__":
main()

OUTPUT
PRACTICAL -22

Ques. Input a list/tuple of elements, search for a given element in the


list/tuple.
Source Code
def search_element(sequence, element):
return element in sequence
def main():
input_sequence = input("Enter elements separated by space:
").split()
search_element_value = input("Enter the element to search: ")
if input_sequence:
if isinstance(input_sequence, list):
result =search_element(input_sequence,
search_element_value)
elif isinstance(input_sequence, tuple):
result = search_element(input_sequence,
search_element_value)
else:
print("Invalid input type. Please enter a valid list or tuple.")
return
if result:
print(f"Element '{search_element_value}' found in the
{type(input_sequence).__name__}.")
else:
print(f"Element '{search_element_value}' not found in the
{type(input_sequence).__name__}.")
else:
print("Input sequence is empty.")
if __name__ == "__main__":
main()

OUTPUT

PRACTICAL -23
Ques. Create a dictionary with the roll number, name and marks for n
students in a class and display the names of students who have scored marks
above 75.
Source Code
def above_75_students(student_dict):
high_scorers = [student['name'] for student in student_dict.values()
if student['marks'] > 75]
return high_scorers
def main():
n = int(input("Enter the number of students: "))
student_dict = {}
for i in range(1, n+1):
roll_number = input(f"Enter roll number for student {i}: ")
name = input(f"Enter name for student {i}: ")
marks = int(input(f"Enter marks for student {i}: "))
student_dict[roll_number] = {'name': name, 'marks': marks}
high_scorers = above_75_students(student_dict)
if high_scorers:
print("\nNames of students who scored above 75:")
for name in high_scorers:
print(name)
else:
print("\nNo students scored above 75.")
if __name__ == "__main__":
main()
OUTPUT
PRACTICAL -24
Ques. Number names of all digits in a given no. using dictionaries.
Source Code
def number_to_words(number):
digit_names = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}
num_str = str(number)
result = [digit_names[digit] for digit in num_str]
return ' '.join(result)
def main():
number = int(input("Enter a number: "))
result = number_to_words(number)
print(f"Number names: {result}")
if __name__ == "__main__":
main()
OUTPUT

PRACTICAL -25
Ques. Menu driven program to Add, Display, Edit, Delete, Search
Doctor’s information using dictionaries (DocId, Name,
Specialization, experience, Salary)
Source Code
def add_doctor(doctor_dict):
doc_id = input("Enter Doctor's ID: ")
name = input("Enter Doctor's Name: ")
specialization = input("Enter Doctor's Specialization: ")
experience = input("Enter Doctor's Experience: ")
salary = input("Enter Doctor's Salary: ")
doctor_dict[doc_id] = {'Name': name, 'Specialization':
specialization, 'Experience': experience, 'Salary': salary}
print("Doctor information added successfully.")
def display_doctors(doctor_dict):
if doctor_dict:
print("\nDoctor Information:")
for doc_id, info in doctor_dict.items():
print(f"DocID: {doc_id}, Name: {info['Name']},
Specialization: {info['Specialization']}, Experience:
{info['Experience']}, Salary: {info['Salary']}")
else:
print("No doctors available.")
def edit_doctor(doctor_dict):
doc_id = input("Enter Doctor's ID to edit: ")
if doc_id in doctor_dict:
print(f"Editing information for Doctor {doc_id}:")
name = input("Enter new Name: ")
specialization = input("Enter new Specialization: ")
experience = input("Enter new Experience: ")
salary = input("Enter new Salary: ")
doctor_dict[doc_id] = {'Name': name, 'Specialization':
specialization, 'Experience': experience, 'Salary': salary}
print(f"Doctor {doc_id} information updated successfully.")
else:
print(f"Doctor {doc_id} not found.")
def delete_doctor(doctor_dict):
doc_id = input("Enter Doctor's ID to delete: ")
if doc_id in doctor_dict:
del doctor_dict[doc_id]
print(f"Doctor {doc_id} deleted successfully.")
else:
print(f"Doctor {doc_id} not found.")
def search_doctor(doctor_dict):
doc_id = input("Enter Doctor's ID to search: ")
if doc_id in doctor_dict:
info = doctor_dict[doc_id]
print(f"\nDoctor Information for {doc_id}:")
print(f"Name: {info['Name']}, Specialization:
{info['Specialization']}, Experience: {info['Experience']}, Salary:
{info['Salary']}")
else:
print(f"Doctor {doc_id} not found.")
def main():
doctors_info = {}
while True:
print("\nChoose an option:")
print("1. Add Doctor")
print("2. Display Doctors")
print("3. Edit Doctor")
print("4. Delete Doctor")
print("5. Search Doctor")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
add_doctor(doctors_info)
elif choice == '2':
display_doctors(doctors_info)
elif choice == '3':
edit_doctor(doctors_info)
elif choice == '4':
delete_doctor(doctors_info)
elif choice == '5':
search_doctor(doctors_info)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number between 1 and
6.")
if __name__ == "__main__":
main()

OUTPUT

You might also like