Python Answers
Python Answers
2.
a)
b)
3.
A)
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
b)
4.
A)
num = int(input("Enter the number: "))
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
b)
sum = 0
for num in range(1, 11):
sum += num
average = sum / 10
print("Sum of first 10 natural numbers:", sum)
print("Average of first 10 natural numbers:", average)
5.
A)
def evennum(data):
for num in data:
if num % 2 == 0:
print(num)
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evennum(data)
b)
elements = []
elements.extend(['Carbon', 'Nitrogen', 'Oxygen', 'Helium'])
print("List after inserting four items:", elements)
sele = 'Helium'
if sele in elements:
print(f"{sele} is present in the list.")
else:
print(f"{sele} is not present in the list.")
dele = 'Nitrogen'
if dele in elements:
elements.remove(dele)
print(f"{dele} deleted from the list.")
else:
print(f"{dele} not found in the list.")
print("List after deleting an element:", elements)
nele = 'Boron'
elements.append(nele)
print(f"{nele} added to the end of the list.")
print("List after adding an element to the end:", elements)
elements.sort(reverse=True)
print("List after arranging in descending order:", elements)
6.
nstr = input("Enter a multi-digit number: ")
freq = {}
for char in nstr:
if char.isdigit():
freq[char] = freq.get(char, 0) + 1
for digit, frequency in freq.items():
print(f"The digit {digit} appears {frequency} time(s) in the number.")
7.
birthdays = {'Arun': 'April 10', 'Bindu': 'Jan 23'}
name = input("Enter a name: ")
if name in birthdays:
print(f"The birthday of {name} is on {birthdays[name]}.")
else:
birthdate = input(f"Enter the birthday of {name}: ")
birthdays[name] = birthdate
print(f"{name} has been added to the dictionary with the birthday
{birthdate}.")
print("Updated Birthday Dictionary:", birthdays)
8.
prime = []
for num in range(2, 101):
isprime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
isprime = False
break
if isprime:
prime.append(num)
print(f"Prime numbers between 1 and 100: {prime}")
9.
A)
def remtup(data, k):
return [t for t in data if len(t) != k]
data = [(1, 2, 3), (4, 5), (6, 7, 8, 9), (10, 11, 12)]
k = int(input("Enter the size: "))
ftuple = remtup(data, k)
print(f"Original data: {data}")
print(f"Data after removing tuples of length {k}: {ftuple}")
b)
def is_palindrome(s):
revstr = s[::-1]
return s == revstr
text = input("Enter a string: ")
text = text.lower()
if is_palindrome(text):
print(f"{text} is a palindrome.")
else:
print(f"{text} is not a palindrome.")
10.
def sort_file(input_file_path, output_file_path):
# Read the contents of the input file
with open(input_file_path, 'r') as file:
lines = file.readlines()
if __name__ == "__main__":
# Replace 'input.txt' and 'output.txt' with your file names
input_file_path = 'input.txt'
output_file_path = 'output.txt'
try:
sort_file(input_file_path, output_file_path)
print("File sorted successfully. Check", output_file_path)
except Exception as e:
print("An error occurred:", str(e))
except Exception as e:
print("Error: ",str(e))
input_filename = 'input.txt'
output_filename = 'sorted_output.txt'
sort_text_file(input_filename, output_filename)
11.
a)
import os
def walkdir(directory):
for root, directories, files in os.walk(directory):
print(f"Exploring: {root}")
print("Subdirectories:")
for subdirectory in directories:
print(f" - {subdirectory}")
print("Files:")
for file in files:
print(f" - {file}")
b)
import os
def delfile():
for filename in os.listdir():
if filename.endswith(".txt"):
file_path = os.path.join(os.getcwd(), filename)
try:
os.remove(file_path)
print(f"Deleted file: {filename}")
except OSError as error:
print(f"Error deleting file {filename}: {error}")
delfile()
12.
import shelve
db = shelve.open("example.db")
db["John Doe"] = {"department": "Engineering", "salary": 50000}
db["Jane Smith"] = {"department": "Marketing", "salary": 45000}
db.close()
db = shelve.open("example.db")
for name, data in db.items():
print(f"Name: {name}")
print(f"Department: {data['department']}")
print(f"Salary: ${data['salary']}")
db.close()