Q1:- WAP that prompts the uses to enter two integer values and displays the result of the
first
number divided by the second, with exactly two decimal place displayed.
ANS.
# Prompting user for input
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Checking if num2 is not zero to avoid division by zero error
if num2 != 0:
# Performing the division
result = num1 / num2
# Displaying the result with two decimal places
print(f"Result: {result:.2f}")
else:
print("Error: Division by zero is not allowed.")
Q2:- WAP in which the user enter either ‘A’,’B’,’C’. If ‘A’ is entered, the program should
display the word Apple, if ‘A’ is entered, the program should the word Apple, if ‘B’ is entered ,
it display Banana and, if ‘C’ is entered, it display ‘Coconut’.
ANS>
# Taking input from the user
user_input = input("Enter 'A', 'B', or 'C': ")
# Checking the input and displaying the corresponding word
if user_input.upper() == 'A':
print("Apple")
elif user_input.upper() == 'B':
print("Banana")
elif user_input.upper() == 'C':
print("Coconut")
else:
print("Invalid input. Please enter 'A', 'B', or 'C'.")
Q3:- WAP to check if given number is prime or not.
ANS>
def is_prime(number):
# A prime number is greater than 1 and has no divisors other than 1 and itself
if number <= 1:
return False
# Check for divisors from 2 to the square root of the number
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False # Found a divisor, not a prime number
return True # No divisors other than 1 and itself, it's a prime number
# Taking input from the user
num = int(input("Enter a number: "))
# Checking if the number is prime
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Q4:- WAP to print Fibonacci series by taking the length from user.
ANS> def fibonacci_series(length):
# Initialize first two Fibonacci numbers
fibonacci_series = [0, 1]
# Generate Fibonacci series
while len(fibonacci_series) < length:
next_number = fibonacci_series[-1] + fibonacci_series[-2]
fibonacci_series.append(next_number)
return fibonacci_series
# Taking input for the length of Fibonacci series from the user
length = int(input("Enter the length of Fibonacci series: "))
# Calling the function to generate Fibonacci series
result = fibonacci_series(length)
# Displaying the Fibonacci series
print("Fibonacci Series:")
print(result)
Q5:- WAP that converts lower case letter to upper case letter and vice-versa.
ANS>
def convert_case(string):
converted_string = ""
for char in string:
# Convert lowercase to uppercase
if char.islower():
converted_string += char.upper()
# Convert uppercase to lowercase
elif char.isupper():
converted_string += char.lower()
else:
converted_string += char # If it's not a letter, keep it as it is
return converted_string
# Taking input from the user
user_input = input("Enter a string: ")
# Calling the function to convert case
converted_result = convert_case(user_input)
# Displaying the converted result
print("Converted String:")
print(converted_result)
Q6:- WAP to program to print a table of given number.
ANS,
def multiplication_table(number):
print(f"Multiplication Table of {number}:")
for i in range(1, 11): # Print table from 1 to 10
print(f"{number} x {i} = {number*i}")
# Taking input from the user
num = int(input("Enter a number to print its multiplication table: "))
# Calling the function to print the multiplication table
multiplication_table(num)
Q7:- WAP that sums a series of (positive) integer entered by the user excluding all numbers that
are greater than 100.
ANS.
def sum_positive_integers():
total_sum = 0
while True:
try:
num = int(input("Enter a positive integer (or 0 to stop): "))
if num == 0:
break # Exit the loop if user enters 0
elif num > 0 and num <= 100:
total_sum += num # Add to total sum if the number is positive and <= 100
else:
print("Number should be positive and less than or equal to 100. Ignoring...")
except ValueError:
print("Invalid input. Please enter a valid positive integer.")
return total_sum
# Calling the function to sum positive integers excluding numbers greater than 100
result = sum_positive_integers()
# Displaying the result
print("Sum of positive integers (excluding numbers > 100):", result)
Q8:- WAP to print the following pattern.
2 2
3 3 3
4 4 4 4
Ans.
def print_pattern(rows):
for i in range(1, rows + 1):
# Print each number i times, from 1 to i
for j in range(1, i + 1):
print(i, end=" ")
print() # Move to the next line after each row
# Taking input from the user for number of rows
num_rows = int(input("Enter the number of rows for the pattern: "))
# Calling the function to print the pattern
print_pattern(num_rows)
Q9:- WAP to print the following pattern
* *
* * *
* * * *
Ans.
def print_pattern(rows):
for i in range(1, rows + 1):
# Print '*' i times, from 1 to i
for j in range(1, i + 1):
print("*", end=" ")
print() # Move to the next line after each row
# Taking input from the user for number of rows
num_rows = int(input("Enter the number of rows for the pattern: "))
# Calling the function to print the pattern
print_pattern(num_rows)
Q10:- W.A.P to perform the following operations on list
(1) max (6)pop
(2) min (7) len
(3) count (8) return
(4) extend (9) append
(5) insert (10) reverse
ANS.
def main():
# Initialize a sample list
my_list = [10, 20, 30, 20, 40, 50]
# Display the original list
print("Original List:", my_list)
while True:
print("\nOperations:")
print("1. Max")
print("2. Min")
print("3. Count")
print("4. Extend")
print("5. Insert")
print("6. Pop")
print("7. Length")
print("8. Return")
print("9. Append")
print("10. Reverse")
print("Enter 'q' to quit")
choice = input("Enter operation number: ")
if choice == '1':
print("Max Value:", max(my_list))
elif choice == '2':
print("Min Value:", min(my_list))
elif choice == '3':
value = int(input("Enter value to count: "))
print(f"Count of {value}: {my_list.count(value)}")
elif choice == '4':
extend_list = [60, 70, 80]
my_list.extend(extend_list)
print("Extended List:", my_list)
elif choice == '5':
index = int(input("Enter index to insert: "))
value = int(input("Enter value to insert: "))
my_list.insert(index, value)
print("List after insertion:", my_list)
elif choice == '6':
popped_value = my_list.pop()
print("Popped Value:", popped_value)
elif choice == '7':
print("Length of List:", len(my_list))
elif choice == '8':
break # Exit the loop
elif choice == '9':
new_value = int(input("Enter value to append: "))
my_list.append(new_value)
print("List after appending:", my_list)
elif choice == '10':
my_list.reverse()
print("Reversed List:", my_list)
elif choice.lower() == 'q':
break # Exit the loop
else:
print("Invalid choice. Please enter a valid operation number.")
print("Final List:", my_list)
if __name__ == "__main__":
main()
Q11:- W.A.P to perform the following operations on dictionary
accessing
updating
adding
Removing
Copy
Clear
Declare
ANS.
def main():
# Declaring a dictionary with the name "John"
my_dict = {
'name': 'John',
'age': 30,
'city': 'New York'
# Display the original dictionary
print("Original Dictionary:", my_dict)
while True:
print("\nOperations:")
print("1. Accessing")
print("2. Updating")
print("3. Adding")
print("4. Removing")
print("5. Copy")
print("6. Clear")
print("7. Declare new dictionary")
print("Enter 'q' to quit")
choice = input("Enter operation number: ")
if choice == '1':
key = input("Enter key to access: ")
if key in my_dict:
print("Value:", my_dict[key])
else:
print("Key not found.")
elif choice == '2':
key = input("Enter key to update: ")
if key in my_dict:
new_value = input("Enter new value: ")
my_dict[key] = new_value
print("Updated Dictionary:", my_dict)
else:
print("Key not found.")
elif choice == '3':
new_key = input("Enter new key: ")
new_value = input("Enter new value: ")
my_dict[new_key] = new_value
print("Dictionary after adding:", my_dict)
elif choice == '4':
key = input("Enter key to remove: ")
if key in my_dict:
del my_dict[key]
print("Dictionary after removing:", my_dict)
else:
print("Key not found.")
elif choice == '5':
# Creating a copy of the dictionary
new_dict = my_dict.copy()
print("Copied Dictionary:", new_dict)
elif choice == '6':
my_dict.clear()
print("Dictionary cleared.")
elif choice == '7':
# Declaring a new dictionary
new_dict = dict()
print("New empty dictionary declared.")
elif choice.lower() == 'q':
break # Exit the loop
else:
print("Invalid choice. Please enter a valid operation number.")
print("Final Dictionary:", my_dict)
if __name__ == "__main__":
main()
Q13:- W.A.P to input the integer values in the list & stores in another list only those values
which are even number & desplays the resulting list.
ANS>
def main():
# Initialize an empty list to store even numbers
even_numbers = []
# Taking input from the user
print("Enter integer values (enter 'q' to stop):")
while True:
user_input = input("Enter an integer (or 'q' to stop): ")
if user_input.lower() == 'q':
break
try:
number = int(user_input)
if number % 2 == 0:
even_numbers.append(number)
except ValueError:
print("Invalid input. Please enter an integer.")
# Display the resulting list of even numbers
print("List of even numbers:", even_numbers)
if __name__ == "__main__":
main()
Q14:- W.A.P to show the concept of multiple inheritance.
ANS.
# Base class 1
class BaseClass1:
def method1(self):
print("Method from BaseClass1")
# Base class 2
class BaseClass2:
def method2(self):
print("Method from BaseClass2")
# Derived class inheriting from BaseClass1 and BaseClass2
class DerivedClass(BaseClass1, BaseClass2):
def method3(self):
print("Method from DerivedClass")
# Creating an instance of DerivedClass
obj = DerivedClass()
# Accessing methods from BaseClass1 and BaseClass2
obj.method1() # Method from BaseClass1
obj.method2() # Method from BaseClass2
# Accessing method from DerivedClass
obj.method3() # Method from DerivedClass
Q15:- Write a menu driven program to add, substract, multiply and divide 2 integer using
function.
# Function to perform addition
def add(a, b):
return a + b
# Function to perform subtraction
def subtract(a, b):
return a - b
# Function to perform multiplication
def multiply(a, b):
return a * b
# Function to perform division
def divide(a, b):
if b != 0:
return a / b
else:
return "Error: Division by zero"
def main():
while True:
print("\nMenu:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Quit")
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '1':
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = add(num1, num2)
print("Result:", result)
elif choice == '2':
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = subtract(num1, num2)
print("Result:", result)
elif choice == '3':
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = multiply(num1, num2)
print("Result:", result)
elif choice == '4':
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = divide(num1, num2)
print("Result:", result)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid input. Please enter a valid choice.")
if __name__ == "__main__":
main()
Q16:- W.A.P that accepts 3 integer and return true if any of the integer is 0, otherwise it returns
false.
ANS> def check_for_zero(num1, num2, num3):
if num1 == 0 or num2 == 0 or num3 == 0:
return True
else:
return False
def main():
# Taking input from the user
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))
num3 = int(input("Enter third integer: "))
# Calling the function to check for 0
result = check_for_zero(num1, num2, num3)
# Displaying the result
if result:
print("True: At least one integer is 0.")
else:
print("False: None of the integers is 0.")
if __name__ == "__main__":
main()
Q17:- write a program to prompt the user to enter a list of words stores in a list only those words
whose first letter occurs within word. The program should display the resulting list?
def filter_words(words):
filtered_words = []
for word in words:
if word[0].lower() in word[1:].lower():
filtered_words.append(word)
return filtered_words
def main():
# Taking input from the user
words = input("Enter a list of words separated by space: ").split()
# Calling the function to filter words
result = filter_words(words)
# Displaying the resulting list
print("Resulting List:")
print(result)
if __name__ == "__main__":
main()
Q18:- W.A.P to do following operations on files:-
Opening
Copy
Remove
Append
Rename
Tell
ANS> import shutil # For file copying and renaming
def create_file(filename):
with open(filename, 'w') as file:
file.write("Hello, this is a sample file.")
def copy_file(source, destination):
shutil.copyfile(source, destination)
print(f"File '{source}' copied to '{destination}'")
def remove_file(filename):
try:
# Remove the file
os.remove(filename)
print(f"File '{filename}' removed successfully.")
except FileNotFoundError:
print(f"File '{filename}' not found.")
def append_file(filename, content):
with open(filename, 'a') as file:
file.write(content + "\n")
print(f"Content appended to '{filename}'")
def rename_file(filename, new_name):
os.rename(filename, new_name)
print(f"File '{filename}' renamed to '{new_name}'")
def tell_file_position(filename):
with open(filename, 'r') as file:
position = file.tell()
print(f"Current position in '{filename}': {position}")
def main():
filename = "sample.txt"
create_file(filename)
while True:
print("\nOperations:")
print("1. Copy File")
print("2. Remove File")
print("3. Append Content to File")
print("4. Rename File")
print("5. Tell Current File Position")
print("6. Exit")
choice = input("Enter operation number: ")
if choice == '1':
new_filename = input("Enter new filename for copy: ")
copy_file(filename, new_filename)
elif choice == '2':
remove_file(filename)
elif choice == '3':
content = input("Enter content to append: ")
append_file(filename, content)
elif choice == '4':
new_name = input("Enter new filename: ")
rename_file(filename, new_name)
elif choice == '5':
tell_file_position(filename)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid operation number.")
if __name__ == "__main__":
main()