a) Write a python program to find factorial of a number.
(Chapter - 2)
Solution:
def fact(n): ans = 1
for i in range(1, n + 1):
ans = i
return ans
n = int(input("Enter a number: "))
result = fact(n) print (f"The factorial of {n} is {result}")
Output: Enter a number: 5
The factorial of 5 is 120
c) Write a python program to check whether a given string is Palindrome or not. (Chapter - 2)
Solution:
def is_palindrome (str): i = 0 j = len(str) 1
while ij:
if str[i] != str[j]:
return False
i += 1
j=1
return True
str = input("Enter a string: ")
if is_palindrome (str):
print(f"{str) is a palindrome.")
else:
print(f"{str) is not a palindrome.")
Output:
Enter a string: madam
madam is a palindrome
b) Write a python program to put even and odd elements of a list into two different lists.(Chapter-3)
Solution:
def separate(mylist):
even_numbers = [] # List to store even numbers
odd_numbers = [] #List to store odd numbers
for num in mylist:
if num % 2 == 0:
even_numbers.append(num)
else: odd_numbers.append(num)
return even_numbers, odd_number
mylist = [1, 2, 3, 4, 5, 6, even_list, odd_list = 7, 8, 9, 10] separate(mylist)
print("Even numbers:" , even_list)
print("Even numbers:" , odd_list)
output:
Even : [2,4,6,8,10]
Odd:[1,3,5,7,9]
a) Write a program to accept a string from user and display the string in reverse order eliminating the letter 's' from the
string. (Chapter - 2)
Solution:
str = input("Enter a string: ")
str1 [Link]('s', '').replace('S', '')
str2 = str1[::-1]
print("Reversed string without 's' or 'S':", str2)
Output:
Enter a string: NSG Academy
Reversed string without 's' or 'S'
b) Write a Solution: program to raise a user defined exception to check if age is less than 18. (Chapter-4)
class InvalidAgeError ( Exception):
def _init_(self.x ).
[Link] x def_str_(self):
def _init(self):
return 'Age less than 18. Invalid: '+str([Link])
class person:
[Link] = input('Enter name:') [Link] int(input('Enter age:'))
if [Link] < 18:
raise InvalidAgeError ([Link]) else:
[Link]() except InvalidAgeError as iae: print(iae
def display(self): print('Name:',[Link]) print('Age:', [Link])
ob = person()
c) Write a python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9).
(Chapter-2)
Solution:
import re
str - input("Enter a string: ")
pattern = "^[a-zA-Z0-9]*$"
if [Link](pattern, str):
print(“the string contains only a-z,A-Z,and 0-9.”)
else:
print("The string contains other characters besides a-z, A-Z, and 0-9.")
Output:
Enter a string: *NSG Academy*
The string contains other characters besides a-z, A-Z, and 0-9
a) Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string
already ends with 'ing', add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. (Chapter-
2)Solution:def modity (str):
if len(str) < 3:return str
elif [Link]('ing'): return str + 'ly'
else:
return str + 'ing'
str= input("Enter a string: ")
result modify(str) print("Modified string:", result)
b) Write a Python program to combine values in a list of dictionaries. Sample date:
[{"item": "item1", "amount":400},{"item":"item2", "amount":300),(item': tem1", "amount":7501] Expected Output: Counter
({'item1":1150", "item2":3001) Solution: ACADEM (Chapter-3)
Solution:
from collections import Counter
data[{'item': 'itemi', 'amount': 400}, {' tem': 'item2', 'amount': 300}, {'item': 'iteml', amount': 750}]
mydictionary = {}
for entry in data:
key entry['item]
entry [‘amount']
if key in mydictionary:
mydictionary [key] += value
else:
mydictionary [key] value
counter = Counter (mydictionary)
print (counter)
Output: Counter({'item1': 1150, 'item2': 300})
c) Write a Python program to extract year, month, date and time using lambda. (Chapter-4)
Solution:
import datetime
get year lambda dt: [Link]
get_month lambda dt: [Link] get_date lambda dt: [Link]
get_time lambda dt: [Link]('%H:%M:%S')
today [Link]()
print("Year:", get_year(today))
print("Month:", get_month(today))
print("Date:", get_date(today)) print("Time:", get_time(today))
Output:Year: 2024
Month: 11
Date: 13
Time: 18:12:26
a) characters Write a program to get a single string from two given strings, separated by space and swap the
first two of each string (Chapter-2)Sample input: 'abc', 'pqr'
Output: pqc abr
Solution:
def swap(str1, str2): word1 = str2[:2] + str1[2:]
word2 str1[:2] + str2[2:]
return word1 + "" + word2
str1 = input("Enter the first string: ") str2 input("Enter the second string: ")
result = swap(str1, str2) print("Output:", result)
Output:Enter the first string: abc
Enter the second string: pqr
Output: pqc abr
c) Write a program to read an entire text file. (Chapter-4)
Solution:
with open('[Link]', 'r') as myfile:
content [Link]()
print(content)
a) Write a python program to Count Vowels and Consonants in a String. (Chapter-2)
Solution:
def count(str):
vowels_string = "aeiouAΕΙΟΥ"
vcnt = 0
ccnt = 0
ch in str:
if [Link]():
if ch in vowels_string:
vcnt += 1
cont += 1
return vent, ccnt
vent, ccnt = count(str)
Output the results
print("Total Number of Vowels is", vcnt)
print("Total Number of Consonants is",ccnt)
Output:Enter a string: nsgacademy
Total Number of Vowels is 3
Total Number of Consonants is 7
b) Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the
values are the square of the keys. (Chapter-3) Sample Dictionary {1: 1, 2:4, 3:9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10:
100, 11: 121, 12: 144, 18:169, 14: 196, 15: 225}
Solution:
squared_dict = {}
for x in range(1, 16):
squared_dict [x] = x**2
print(squared_dict)
Output: (1:1, 2:4, 3:9, 4: 16, 5: 25, 6: 36, 7:49, 864, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
c) Write a Python function that accepts a string and counts the number of upper and lower case letters. (Chapter -2)
Solution:
def count(str): ucnt = 0 1cnt = 0
for char in str:
if [Link]():
elif [Link]():
1cnt
str input("Enter a string: ") ucnt, lcnt = count(str)
print("Uppercase letters:", ucnt) print("Lowercase letters:", lcnt)
Output:Enter a string: NSG Academy
Uppercase letters: 4
Lowercase letters: 6
b) Write a Python program to find ged of a number using recursion. (Chapter - 3)
Solution:
def gcd(a, b): if (b=0): return a else: return gcd(b,a%b)
a=int(input('Enter a number: '))
b=int(input('Enter another number: '))
x=gcd(abs(a),abs(b))
print("The ged of",a,"and",b,"is",x)
Output
Enter a number: 12
Enter another number: 39
The gcd of 12 and 39 is 3
[Link] a Python Solution: program to check if a given key already exists in a dictionary. (Chapter-3)
def checkKey(book, k):
if k in [Link]():
print("Book is present")
print("Auther Nameis",book[k])
else:
print("Book is not present")
mybook = {'book':'python','publication': 'vision','author': 'Suresh Agrawal'}
key = 'author'
checkKey(mybook, key)
Output
Book is present
Author Name is SureshAgrawal
[Link] a Python program to print even length words in a string. (Chapter-2) Solution:
str = input('Enter a string: ') words [Link](" ")
print('Even length words in given string are as follows')
for w in words:
if len(w) % 2 0:
print(w)
Output: Enter a string: Python was developed by Guido van Rossum Even length words in given string are as follows
Python by Rossum
a) Write a Python program to check for Zero Division Error Exception. (Chapter - 4)
Solution:a=int(input("Enter a number:"))
b=int(input("Enter another number:"))
try:if b-0:
raise ZeroDivisionError
else:c = a/b
print('Result: ',c)
except ZeroDivisionError: print('Can\'t divide by zero')
print("ZeroDivisionError occurred and handled")
Output
Enter a number:5
Enter another number:0
Can't divide by zero
ZeroDivisionError occurred and handled
a) Write a Python program to check if a given number is Armstrong. (Chapter-2)
Solution: noint(input('Enter a number:'))
nol = no
sum = 0
while(no>0):
d=no%10
sumsum+ (d**3)
nono//10
if sum-nol:
print(no1, 'is armstrong number')
else:
print(no1, 'is not armstrong number')
Output:
Enter a number: 153 153 is armstrong number
[Link] a Python program to display power of 2 using anonymous function. (Chapter-3)
Solution:
terms int(input("Enter the number of terms? "))
result list(map(lambda x: 2 **x, range(terms)))
print("The total number of terms:", terms) for i in range(terms):
print("2 raised to power", i, "is", result[i])
Output:
Enter the number of terms? 10
The total number of terms: 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256 2 raised to power 9 is 512
Q. the function enumerate().(Chapter - 2)
Solution:
enumerate() function adds a counter to an iterable as the key and returns it in a form of enumerating object.
Syntax:
enumerate(iterable, start)
where,
iterable is any object that supports iteration and start is the index number from which the counter is to be started, by
default it is O
Example:
colors = ['red', 'green', 'blue'] for x in enumerate(colors):
print(x) mylist= list(enumerate(colors))
print(mylist)
Output
(0, 'red')
(1, 'green')
(2, 'blue')
[(0, 'red'), (1, 'green'), (2, 'blue')]
[Link] the extend method of list. (Chapter - 3)
Solution: The extend() method adds each element of the passed iterable to the end of the current list.
Syntax:
[Link](iterable)
terable iterable may be string, list, set, tuple etc
where.
Example:
mylist[11,22,33] mylist1 = [44,55] [Link](mylist1) print(mylist)
Output
[11, 22, 33, 44, 55]
a) Write a python program to calculate XY. (Chapter - 2)
Solution: def power (x,y): ans = 1
while y>0:
ans ans * x
y-=1 return ans
x = int(input('Enter value ) of X:'))
y = int(input('Enter value of Y:')) ans = power (x,y)
print('Result of', x, 'raise to', y,':', ans)
b) Write a python program to accept a number and check whether it is perfect number or [Link]-2)
Solution:
def isPerfect(n):
sum=0
for I in range(1,n):
if n%i==0:
sum += i
return sum==n
n = int(input('Enter a number:'))
ans = isPerfect (n)
if ans == True:
print(n, 'is a perfect number')
else:
print(n, 'is not a perfect number')
b) Write a program in python to accept 'n' integers in a list, compute & display addition of all squares of theses integers.
(Chapter - 3)
Solution:
mylist = []
nint(input('Enter how many integers:'))
print('Enter', n, 'integers:') for i in range(n):
x = int(input())
[Link](x)
print("List of integers: " + str(mylist))
ans = sum([x**2 for x in mylist])
print("The sum of squares of these integers : “+str(ans))
d) Demonstrate list slicing. (Chapter-3)
Solution:
List slicing allows us to create a new list by extracting a portion of an existing list.
Syntax:
list[start:stop:step]
where, 'start' is the index of the first element, 'stop' is the index of the first element not to be included, and 'step' is the step
size between elements.
Example:
mylist [10, 11, 22, 33, 44, 55, 66, 77, 88, 99]
subset1
mylist [2:6]
subset2 mylist[4:8]
subset3 mylist[:5]
subset4 mylist[7:]
print("Original List:", mylist)
print("Subset1:", subset1)
print("Subset2:", subset2)
print("Subset3:", subset3)
print("Subset4:", subset4)
subset5 mylist[1:9:2]
subset6 mylist[::3]
print("Subset5:", subset5)
print("Subset6:", subset6)
Output:
Original List: [10, 11, 22, 33, 44, 55, 66 , 77, 88, 99]
Subset1: [22, 33, 44, 55]
Subset2: [44, 55, 66, 77]
Subset3: [10, 11, 22, 33, 44]
Subset4: [77, 88, 99]
Subset5: [11, 33, 55, 77]
Subset6: [10, 33, 66, 99]
c) Write a Python program to count all "[Link]" (Chapter - 4) import string occurrences of “india” and "Country" in a
text file “[Link]”
Solution:
Import string
word1 = "India"
word2 "Country"
cnt1=0
cnt2 = 0
with open("[Link]", 'r') as myfile:
for line in myfile:
line [Link]()
words [Link](" ")
for win words:
if(w== word1):
cnt1= cnt1 + 1
if(w== word2):
cnt2 cnt2 + 1
print("Occurrences of the word", word1, ":", cnt1)
print("Occurrences of the word", word2, ":", cnt2)