Python Imp Questions Krishna 36 Full_Final
Python Imp Questions Krishna 36 Full_Final
1. Python program to check whether a string is palindrome or 4.Check if a Number is an Armstrong Number
not num = int(input("Enter a number: "))
string = input("Enter a string: ") sum_of_digits = 0
if string == string[::-1]: temp = num
print("Palindrome") order = len(str(num))
else: while temp > 0:
print("Not a palindrome") digit = temp % 10
print("Executed by Krishna Israni 36") sum_of_digits += digit ** order
temp //= 10
if num == sum_of_digits:
print("Armstrong number")
else:
print("Not an Armstrong number")
print("Executed by Krishna Israni 36")
2.Python Program to Check Leap Year 5.Count the Occurrence of Each Character in a String
year = int(input("Enter a year: ")) string = input("Enter a string: ")
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): for ch in string:
print(ch, "=", string.count(ch))
print("Leap year")
else: print("Performed by Krishna Israni 36")
print("Not a leap year")
print("Executed by Krishna Israni 36")
3.Python Program to Print all Prime Numbers in an Interval 6. Find the Common Elements Between Two Lists
start = int(input("Enter start of range: ")) list1 = [5, 2, 3, 4, 1]
end = int(input("Enter end of range: ")) list2 = [1, 5, 6, 7, 2]
for num in range(start, end + 1): common = []
if num > 1: for item in list1:
for i in range(2, num): if item in list2:
if num % i == 0: common.append(item)
break print("Common elements:", common)
else: print("Performed By Krishna Israni 36")
print(num, end=" ")
print("\nExecuted by Krishna Israni 36")
Tuple – Krishna Israni 36
1.Count the occurrences of an element in a tuple .2. Merge two tuples and remove duplicates
CODE: CODE:
t = (1, 2, 3, 2, 4, 2, 5) tuple1 = (1, 2, 3,5)
element = int(input("Enter the element to count: ")) tuple2 = (2, 4, 5, 6)
count = t.count(element) merged_tuple = tuple(set(tuple1 + tuple2))
print(merged_tuple)
print(f"{element} occurs {count} times in the tuple") print("Executed by Krishna Israni 36")
print("Performed By Krishna Israni 36")
3 .Find the first and last elements of a tuple. 4.Find the difference between two tuples.
CODE : CODE:
my_tuple = (200, 20, 30, 40, 100) tuple1 = (1, 2, 3, 4, 5)
first_element = my_tuple[0] tuple2 = (3, 2, 5, 6, 7)
last_element = my_tuple[-1] difference = tuple(set(tuple1) - set(tuple2))
print(first_element, last_element) print(difference)
5. Check if a tuple is a subset of another tuple. 6. Find the frequency of each element in a tuple.
tuple1 = (1, 2, 3) my_tuple = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
tuple2 = (1, 2, 3, 4, 5) frequency = {}
is_subset = set(tuple1).issubset(set(tuple2)) for i in my_tuple:
print(is_subset) if i in frequency:
print("Executed by Krishna Israni 36") frequency[i] += 1
else:
frequency[i] = 1
print(frequency)
print("Executed by Krishna Israni 36")
Dictionary- Krishna Israni 36
1.Create a dictionary with default values using the 2. Count the number of occurrences of each character in a
dict.fromkeys() method. string using a dictionary.
CODE: CODE:
keys = ['a', 'b', 'c'] text = "hello"
default_value = 36 char_count = {}
my_dict = dict.fromkeys(keys, default_value) for char in text:
print(my_dict) if char in char_count:
print("Executed by Krishna Israni 36") char_count[char] += 1
else:
char_count[char] = 1
print(char_count)
print("Executed by Krishna Israni 36")
3 . Check if two dictionaries are equal. and Merge two 4.Create a dictionary where the values are squares of the
dictionaries. keys.
CODE : CODE:
dict1 = {'a': 1, 'b': 2} keys = [1, 2, 3, 4, 5]
dict2 = {'a': 1, 'b': 2} squares_dict = {}
print(dict1 == dict2) for k in keys:
dict3 = {'c': 3, 'd': 4} squares_dict[k] = k ** 2
dict1.update(dict3) print(squares_dict)
print(dict1) print("Executed by Krishna Israni 36")
print("Executed by Krishna Israni 36")
5. Find the key with the maximum value in a dictionary. 6. Sort a dictionary by its keys..
my_dict = {'a': 10, 'b': 25, 'c': 15} my_tuple = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
max_key = None frequency = {}
max_value = float('-inf') for i in my_tuple:
for key, value in my_dict.items(): if i in frequency:
if value > max_value: frequency[i] += 1
max_value = value else:
max_key = key frequency[i] = 1
print(max_key) print(frequency)
print("Executed by Krishna Israni 36") print("Executed by Krishna Israni 36")
String – Krishna Israni 36
1.Python Program to Sort Words in Alphabetic Order. 2. Python Program to Remove Punctuation From a String
CODE: CODE:
text = input("Enter a sentence: ") import string
words = text.split()
words.sort() text = input("Enter a sentence: ")
print("Sorted words:") clean_text = text.translate(str.maketrans("", "",
for word in words: string.punctuation))
print(word)
print("Executed By: Krishna Israni 36") print("Text without punctuation:", clean_text)
print("Executed By: Krishna Israni 36")
3 .Python Program to generate a Random String 4.Count the Occurrence of Each Character in a String
CODE : CODE:
import random text = input("Enter a string: ")
import string char_count = {}
for char in text:
print("Random String:", char_count[char] = char_count.get(char, 0) + 1
''.join(random.choices(string.ascii_letters, k=10))) for char, count in char_count.items():
print("Executed by Krishna Israni 36") print(f"{char}: {count}")
print("Executed by Krishna Israni 36")
5. Find the Common Elements Between Two Lists 6. Python program to check whether a string is palindrome
list1 = input("Enter first list: ").split() or not
list2 = input("Enter second list: ").split() CODE:
common = [] def is_palindrome(s):
for item in list1: s = s.lower().replace(" ", "")
if item in list2 and item not in common: return s == s[::-1]
common.append(item) word = input("Enter a word: ")
print("Common elements:", common) if is_palindrome(word):
print("Executed by Krishna Israni 36") print("It's a palindrome!")
else:
print("Not a palindrome.")
print("Executed by Krishna Israni 36")
List - Krishna Israni 36
1.Python Program to compare two lists 4.Python Program to convert List to Set
CODE: CODE:
list1=[1,2,4] lst = [1, 2, 2, 3, 4, 4, 5]
list2=[1,2,3] unique_set = set()
print(list1==list2) for item in lst:
print("Executed by Krishna Israni 36") unique_set.add(item)
print(unique_set)
print("Executed by Krishna Israni 36")
2.Python Program to convert list to dictionary 5. Python Program to convert list to string
CODE: CODE:
keys = ["a", "b", "c"] lst = ["Hello", "World"]
values = [1, 2, 3] result = ""
dictionary = {} for item in lst:
for i in range(len(keys)): result += item + " "
dictionary[keys[i]] = values[i] print(result.strip())
print(dictionary) print("Executed by Krishna Israni 36")
print("Executed by Krishna Israni 36")
3. Python Program to add two lists 6. Write a Python function that returns the second largest
CODE: element in a list of numbers.
list1 = [1, 2, 3] CODE:
list2 = [4, 5, 6] def second_largest(lst):
result = [] largest = second = float('-inf')
for i in range(len(list1)): for num in lst:
result.append(list1[i] + list2[i]) if num > largest:
print(result) second, largest = largest, num
print("Executed by Krishna Israni 36") elif num > second and num != largest:
second = num
return second
2.Python Program to Make a Simple Calculator 5.Python Program to Find Factorial of Number Using
def calculator(a, b, op): Recursion
if op == '+': return a + b def fact(n):
if op == '-': return a - b if n == 0:
if op == '*': return a * b return 1
if op == '/': return a / b if b != 0 else "Cannot divide by return n * fact(n - 1)
zero"
return "Invalid operator" num = int(input("Enter a number: "))
a = int(input("Enter first number: ")) print("Factorial:", fact(num))
b = int(input("Enter second number: ")) print("Executed by Krishna Israni 36")
op = input("Enter operator (+, -, *, /): ")
print("Result:", calculator(a, b, op))
print("Executed by Krishna Israni 36")
3. Python program to print all numbers between 1 to 100 6.Write a function that merges two sorted lists into one
for num in range(1, 101): sorted list.
temp, sum, power = num, 0, len(str(num)) def merge_sorted_lists(list1, list2):
while temp > 0: return sorted(list1 + list2)
sum += (temp % 10) ** power
temp //= 10 list1 = [1, 3, 5]
power -= 1 list2 = [2, 4, 6]
if sum == num: print(merge_sorted_lists(list1, list2))
print(num, end=" ") print("Executed by Krishna Israni 36")
print("\nExecuted by Krishna Israni 36")
IMP Program-Krishna Israni 36
1.Write python program to display output like. 4. Write down the output of the following Python code:
rows = 3
num = 2 indices = ['zero', 'one', 'two', 'three', 'four', 'five']
for i in range(1, rows + 1): print(indices[:4])
for j in range(i * 2 - 1): print(indices[-2:])
print(num, end=" ") print("Executed by Krishna Israni 36")
num += 2
print()
print("Executed by Krishna Israni 36")
2.Write a program to print following: 5. Create a parent class named Animals and a child class
for i in range(1, 5): Herbivorous which will extend the class Animal. In the
for j in range(1, i + 1): child class Herbivorous over side the method feed(). Create
print(j, end=" ") object of the class Herbivorous and call the method feed
print() class Animals:
print("Executed by Krishna Israni 36") def feed(self):
print("Animals eat food.")
class Herbivorous(Animals):
def feed(self):
print("Herbivorous animals eat plants.")
obj = Herbivorous()
obj.feed()
print("Executed by Krishna Israni 36")
3.Write the output of the following: 6. Design a class Student with data members: name, roll
i) a = [2, 5, 1, 3, 6, 9, 7] number, department, and mobile number. Create suitable
a[2:6] = [2, 4, 9, 0] methods for reading and printing student information.
print(a) class Student:
def __init__(self, name, roll_no, dept, mobile):
self.name = name
self.roll_no = roll_no
self.dept = dept
self.mobile = mobile
def display(self):
print("Student Details:")
print("Name:", self.name)
print("Roll No:", self.roll_no)
print("Department:", self.dept)
print("Mobile:", self.mobile)
ii) b = ["Hello", "Good"] name = input("Enter Name: ")
b.append("python") roll_no = input("Enter Roll Number: ")
print(b) dept = input("Enter Department: ")
mobile = input("Enter Mobile Number: ")
filename = "sample.txt"
count_characters(filename)
2. Write a Python program to create a user-defined 5. Write a program to open a file in write mode and
exception called NegativeValueError and raise it if the append some contents at the end of the file.
user enters a negative number. def write_and_append(filename, initial_content,
CODE: append_content):
class NegativeValueError(Exception): with open(filename, 'w') as file:
pass file.write(initial_content + "\n")
3 .Write a program where a function withdraw(amount) 6.Write a Program to count and display total no of
raises InsufficientBalanceException if the withdrawal charcters after first 20 characters in a file.
amount is more than the balance. CODE:
CODE : def count_characters_after_20(filename):
class InsufficientBalanceException(Exception): with open(filename, 'r') as file:
pass file.seek(20)
content = file.read()
def withdraw(amount, balance):
if amount > balance: remaining_chars = len(content)
raise InsufficientBalanceException("Insufficient balance print("Total characters after first 20:", remaining_chars)
for withdrawal.")
balance -= amount filename = "sample.txt"
print("Withdrawal successful. Remaining balance:", count_characters_after_20(filename)
balance)
print("Executed by Krishna Israni 36")
try:
balance = 1000 # Example balance
amount = int(input("Enter withdrawal amount: "))
withdraw(amount, balance)
except InsufficientBalanceException as e:
print("Error:", e)
except ValueError:
print("Please enter a valid integer.")
print("Executed by Krishna Israni 36")