0% found this document useful (0 votes)
7 views9 pages

Extra Questions

The document contains a collection of Python programs covering various topics such as string manipulation, number checks, tuple operations, dictionary handling, and list operations. Each program is accompanied by a brief description and is attributed to the author, Muskan Kateja, Roll No. 17, CO6IA. The programs serve as examples for basic Python functionalities and include tasks like checking for palindromes, counting character occurrences, and merging lists.

Uploaded by

AAYUSH TIKONE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Extra Questions

The document contains a collection of Python programs covering various topics such as string manipulation, number checks, tuple operations, dictionary handling, and list operations. Each program is accompanied by a brief description and is attributed to the author, Muskan Kateja, Roll No. 17, CO6IA. The programs serve as examples for basic Python functionalities and include tasks like checking for palindromes, counting character occurrences, and merging lists.

Uploaded by

AAYUSH TIKONE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Basic Programs

Q1. Write a Python program to check


whether a string is palindrome or not. Q4. Write a Python program to check
Armstrong number.
string = input("Enter a string: ")
if string == string[::-1]: num = 153
print("'" + string + "' is a palindrome.") sum = sum(int(d)**len(str(num)) for d in
else: str(num))
print("'" + string + "' is not a
palindrome.") print(num, "is an Armstrong number." if
print("Programmed by Muskan Kateja, Roll num == sum else "is not an Armstrong
No. 17, CO6IA") number.")
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

Q2. Write a Python program to check


leap year. Q5. Write a Python program to count the
occurrence of each character in a string.
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or string = input("Enter a string: ")
(year % 400 == 0): count = {}
print(f"{year} is a leap year.") for char in string:
else: count[char] = count.get(char, 0) + 1
print(f"{year} is not a leap year.") print("Character occurrences:")
print("Programmed by Muskan Kateja, Roll for char, freq in count.items():
No. 17, CO6IA") print(f"'{char}': {freq}")
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")
Q3. Write a Python program to print all
prime numbers in an interval.

start, end = 10, 50


print("Prime numbers between", start, "and",
end, ":")
for num in range(start, end + 1): Q6. Write a Python program to find the
if num > 1 and all(num % i != 0 for i in common elements between two lists.
range(2, int(num ** 0.5) + 1)): list1 = [1, 2, 3, 4, 5]
print(num, end=" ") list2 = [4, 5, 6, 7, 8]
print("\nProgrammed by Muskan Kateja, print("Common elements:", list(set(list1) &
Roll No. 17, CO6IA") set(list2)))
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

Tuple
7. Count the occurrences of an element
in a tuple t1 = (1, 2, 3, 4, 5)
t2 = (4, 5, 6, 7)
t = (1, 2, 3, 4, 2, 5, 2) difference = tuple(set(t1) - set(t2))
print("Count of 2:", t.count(2)) print("Difference:", difference)
print("Programmed by Muskan Kateja, Roll print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA") No. 17, CO6IA")

8. Merge two tuples and remove 11. Check if a tuple is a subset of


duplicates another tuple
t1 = (1, 2, 3, 4)
t2 = (3, 4, 5, 6) t1 = (1, 2, 3)
merged = tuple(set(t1 + t2)) t2 = (1, 2, 3, 4, 5)
print("Merged tuple:", merged) print("Is t1 a subset of t2?",
print("Programmed by Muskan Kateja, Roll set(t1).issubset(t2))
No. 17, CO6IA") print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

9. Find the first and last elements of a


tuple 12. Find the frequency of each
element in a tuple
t = (10, 20, 30, 40, 50)
print("First element:", t[0]) t = (1, 2, 2, 3, 4, 4, 4, 5)
print("Last element:", t[-1]) freq = {x: t.count(x) for x in set(t)}
print("Programmed by Muskan Kateja, Roll print("Frequency:", freq)
No. 17, CO6IA") print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

10. Find the difference between two


tuples

Dictionary
13. Create a dictionary with default
values using the dict.fromkeys() method

keys = ['a', 'b', 'c']


default_value = 0
16. Create a dictionary where the
d = dict.fromkeys(keys, default_value) values are squares of the keys
print("Dictionary with default values:", d)
print("Programmed by Muskan Kateja, Roll keys = [1, 2, 3, 4, 5]
No. 17, CO6IA") squares = {k: k**2 for k in keys}
print("Squares dictionary:", squares)
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")
14. Count the number of occurrences
of each character in a string using a
dictionary
17. Find the key with the maximum
value in a dictionary
s = "hello world"
d = {}
d = {'a': 10, 'b': 25, 'c': 15}
for char in s:
max_key = max(d, key=d.get)
d[char] = d.get(char, 0) + 1
print("Key with max value:", max_key)
print("Character occurrences:", d)
print("Programmed by Muskan Kateja, Roll
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")
No. 17, CO6IA")

18. Sort a dictionary by its keys


15. Check if two dictionaries are equal
and merge two dictionaries
d = {'b': 2, 'a': 1, 'c': 3}
d1 = {'a': 1, 'b': 2} sorted_dict = dict(sorted(d.items()))
d2 = {'a': 1, 'b': 2} print("Sorted dictionary:", sorted_dict)
print("Dictionaries are equal:", d1 == d2) print("Programmed by Muskan Kateja, Roll
d1.update({'c': 3}) No. 17, CO6IA")
print("Merged dictionary:", d1)
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

String
s = "python programming is fun"
19. Python program to sort words in words = s.split()
alphabetical order
words.sort()
print("Sorted words:", " ".join(words)) def is_palindrome(s):
print("Programmed by Muskan Kateja, Roll return s == s[::-1]
No. 17, CO6IA") s = "madam"
print("Palindrome" if is_palindrome(s) else
"Not a palindrome")
print("Programmed by Muskan Kateja, Roll
20. Python program to remove No. 17, CO6IA")
punctuation from a string
import string
s = "Hello, World! How's it going?"
clean = "".join(c for c in s if c not in 23. Python program to reverse words
string.punctuation) in a string while keeping character
print("Without punctuation:", clean) order
print("Programmed by Muskan Kateja, Roll s = "hello world"
No. 17, CO6IA") reversed_words = " ".join(word[::-1] for
word in s.split())
print("Reversed words:", reversed_words)
print("Programmed by Muskan Kateja, Roll
21. Python program to generate a No. 17, CO6IA")
random string
import random, string
length = 8
rand_str = 24. Python program to find all
''.join(random.choices(string.ascii_letters + occurrences of a substring and return
string.digits, k=length)) starting indices
print("Random string:", rand_str)
s = "ababcabcab"
print("Programmed by Muskan Kateja, Roll
sub = "abc"
No. 17, CO6IA")
indices = [i for i in range(len(s)) if
s.startswith(sub, i)]
print("Occurrences at indices:", indices)
print("Programmed by Muskan Kateja, Roll
22. Python function to check whether No. 17, CO6IA")
a given string is a palindrome or not

List
list1 = [1, 2, 3, 4]
25. Python program to compare two list2 = [1, 2, 3, 4]
lists
print("Lists are equal" if list1 == list2 else list1 = [1, 2, 2, 3, 4, 4, 5]
"Lists are not equal") s = set(list1)
print("Programmed by Muskan Kateja, Roll print("Set:", s)
No. 17, CO6IA") print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

26. Python program to convert list to


dictionary 29. Python program to convert list to
string
keys = ['name', 'age', 'city']
values = ['Muskan', 21, 'Mumbai'] list1 = ['Hello', 'World']
s = " ".join(list1)
d = dict(zip(keys, values)) print("String:", s)
print("Dictionary:", d) print("Programmed by Muskan Kateja, Roll
print("Programmed by Muskan Kateja, Roll No. 17, CO6IA")
No. 17, CO6IA")

30. Python function to return the


27. Python program to add two lists second largest element in a list
list1 = [1, 2, 3] def second_largest(lst):
list2 = [4, 5, 6] unique = list(set(lst))
unique.sort()
result = [x + y for x, y in zip(list1, list2)] return unique[-2] if len(unique) > 1 else
print("Sum of lists:", result) "No second largest"
print("Programmed by Muskan Kateja, Roll nums = [10, 20, 30, 40, 40]
No. 17, CO6IA") print("Second largest element:",
second_largest(nums))
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

28. Python program to convert list to


set
Python Function Programs
print("Programmed by Muskan Kateja, Roll
31. Python program to find HCF No. 17, CO6IA")
import math
a, b = 36, 60
print("HCF:", math.gcd(a, b))
32. Python program to make a simple print("Fibonacci sequence:", [fib(i) for i in
calculator range(10)])
print("Programmed by Muskan Kateja, Roll
a, b = 10, 5
No. 17, CO6IA")
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Programmed by Muskan Kateja, Roll 35. Python program to find factorial of
No. 17, CO6IA") a number using recursion
def fact(n):
return 1 if n == 0 else n * fact(n-1)
print("Factorial of 5:", fact(5))
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")
33. Python program to print all
disarium numbers between 1 to 100
def is_disarium(n):
return n == sum(int(d)**(i+1) for i, d in
36. Python function to merge two
enumerate(str(n)))
sorted lists into one sorted list
print("Disarium numbers:", [n for n in
range(1, 101) if is_disarium(n)]) def merge_sorted(l1, l2):
print("Programmed by Muskan Kateja, Roll return sorted(l1 + l2)
No. 17, CO6IA") list1 = [1, 3, 5]
list2 = [2, 4, 6]
print("Merged list:", merge_sorted(list1,
list2))
print("Programmed by Muskan Kateja, Roll
34. Python program to display No. 17, CO6IA")
Fibonacci sequence using recursion
def fib(n):
return n if n <= 1 else fib(n-1) + fib(n-2)

IMP PROGRAMS
print(num, end=" ")
37. Python program to display the num += 2
pattern using loops print()
rows = [1, 3, 5] print("Programmed by Muskan Kateja, Roll
num = 2 No. 17, CO6IA")
for r in rows:
for col in range(r):
40. Output of the following Python
code
indices = ['zero', 'one', 'two', 'three', 'four',
'five']
38. Python program to print the print(indices[:4])
triangle pattern using loops print(indices[-2:])
for i in range(1, 5): print("Programmed by Muskan Kateja, Roll
for j in range(1, i + 1): No. 17, CO6IA")
print(j, end=" ")
print()
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA") 41. Python program with parent and
child class using method overriding
class Animals:
def feed(self):
print("Animals eat food")
39. Output of the following code class Herbivorous(Animals):
def feed(self):
i)a = [2, 5, 1, 3, 6, 9, 7] print("Herbivorous eat plants")
a[2:6] = [2, 4, 9, 0] h = Herbivorous()
print(a) h.feed()
print("Programmed by Muskan Kateja, Roll print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA") No. 17, CO6IA")

ii)b = ["Hello", "Good"]


42.Design a class Student with data
b.append("python")
members: name, roll number,
print(b)
department, and mobile number. Create
print("Programmed by Muskan Kateja, Roll
suitable methods for reading and printing
No. 17, CO6IA")
student information.
class Student:
def __init__(self, name, roll, dept,
iii)t1 = [3, 5, 6, 7] mobile):
print(t1[2]) self.name = name
print(t1[-1]) self.roll = roll
print(t1[2:]) self.dept = dept
print(t1[:]) self.mobile = mobile

def display(self):
print(self.name, self.roll, self.dept,
self.mobile) print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")
s = Student("Muskan", 17, "CO",
"9876543210")
s.display()

FILE HANDLING AND EXCEPTION HANDLING


withdrawal amount is more than the
43. Python program to read a file line by balance
line and count the number of words in class
each line InsufficientBalanceException(Exception):
with open("file.txt", "r") as f: pass
for line in f: balance = 1000
print("Words in line:", len(line.split())) amount = int(input("Enter withdrawal
print("Programmed by Muskan Kateja, Roll amount: "))
No. 17, CO6IA") try:
if amount > balance:
raise
InsufficientBalanceException("Insufficient
44. Python program to create a balance!")
user-defined exception called else:
NegativeValueError and raise it if the balance -= amount
user enters a negative number print("Withdrawal successful")
except InsufficientBalanceException as e:
class NegativeValueError(Exception): print(e)
pass print("Programmed by Muskan Kateja, Roll
num = int(input("Enter a number: ")) No. 17, CO6IA")
try:
if num < 0:
raise NegativeValueError("Negative
value entered!")
except NegativeValueError as e:
print(e) 46. Python program to count no. of
print("Programmed by Muskan Kateja, Roll vowels, consonants, total characters, and
No. 17, CO6IA") spaces in a given file
vowels = consonants = spaces = chars = 0
with open("file.txt", "r") as f:
for line in f:
45. Python program where for ch in line:
withdraw(amount) raises if ch.isalpha():
InsufficientBalanceException if the if ch.lower() in "aeiou":
vowels += 1
else:
consonants += 1
elif ch.isspace():
spaces += 1
chars += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Spaces:", spaces)
print("Total characters:", chars)
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

47. Python program to open a file in write


mode and append some contents at the
end of the file
with open("file.txt", "w") as f:
f.write("This is the initial content.\n")
with open("file.txt", "a") as f:
f.write("Appended content here.\n")
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

48. Python program to count and display


the total number of characters after the
first 20 characters in a file
with open("file.txt", "r") as f:
content = f.read()[20:]
print("Characters after first 20:",
len(content))
print("Programmed by Muskan Kateja, Roll
No. 17, CO6IA")

You might also like