21761A5422 Python
21761A5422 Python
1. Implement Python Script for checking the given year is leap year or not
Solution:
n = input("Please enter year")
year = int (n)
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
Output:
Please enter year 2021
2021 is Not the Leap Year
n = input("Please enter year")
year = int (n)
if (year%400 == 0):
print("%d is a Leap Year" %year)
elif (year%100 == 0):
print("%d is Not the Leap Year" %year)
elif (year%4 == 0):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
output:
# Python program to check the given year is leap or not using nested if
statement
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:
if val == True:
print("% s is a Leap Year" % year)
else:
print("% s is not a Leap Year" % year)
Output:
Please enter year 2019
2019 is not a Leap Year
Solution:
lst = []
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
Solution
test_num = 0
while(num>0):
remainder = num % 10
num = num//10
print("The reverse number is : {}".format(test_num))
Output:
Please enter any number: 221
The reverse number is : 122
Solution:
Verifying for 3 digit numbers
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:
Solution:
num=int(input("Enter any number:"))
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The {0} number is palindrome!".format(temp))
else:
print("Not a palindrome!")
Output:
1
2
Enter any number: 121
This 121 number is palindrome!
reverse= 0
def integer_reverse(number):
global reverse
if(number > 0):
Reminder = number % 10
reverse = (reverse * 10) + Reminder
integer_reverse(number // 10)
return reverse
number = int(input("Enter any Number: "))
rev = integer_reverse(number)
if(number == rev):
print("The %d is a Palindrome Number" %number)
else:
print("The %d is not a Palindrome Number" %number)
Output:
1
2
Please Enter any Number: 151
The 151 is a Palindrome Number
7. Implement Python Script to print factorial of number
Solution:
num = int(input("Enter a number: "))
print("The factors of {} are,".format(num))
for i in range(1,num+1):
if num % i == 0:
print(i)
Output:
Enter a number: 10
The factors of 10 are,
1
2
5
10
Python Program to Find the Factors of a Number by using Functions
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("Enter a number: "))
print_factors(num)
Output:
Enter a number: 10
The factors of 10 are,
1
2
5
10
8. Implement Python Script to print all prime numbers within the given range
Solution:
Program to Check A given Number is Prime Or Not
Num = int(input(" Please Enter any Number: "))
count = 0
for i in range(2, (Num//2 + 1)):
if(Num % i == 0):
count = count + 1
break
if (count == 0 and Num != 1):
print(" %d is a Prime Number" %Num)
else:
print(" %d is not a Prime Number" %Num)
Output
Please Enter any Number: 50
50 is not a Prime Number
Python Program To Print Numbers From 1 to N Using For Loop
# Python Program to print n prime number using for loop
Output:
Please Enter any Number: 25
Prime numbers between 1 and 25 are:
2 3 5 7 11 13 17 19 23
Python Program To Print Numbers From 1 to N Using While Loop
# Python Program to print Prime Numbers from 1 to N
Number = 1
sum = 0
i=2
Solution:
n = int(input('Enter the value of n: '))
x = int(input('Enter the value of x: '))
sum_of_series = 0
for i in range(n+1):
sum_of_series += pow(x,i)
print('Sum of the series is:', sum_of_series)
*
* *
* * *
* * * *
* * * * *
Solutio
rows = int(input("Enter number of rows: "))
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
Output:
*
* *
* * *
* * * *
* * * * *
MODULE I: Exercise Programs on Python Lists
Solution:
# Using list.reverse() to reverse a list in Python
values = [1, 2, 3, 4, 5]
values.reverse()
print(values)
Output: [5, 4, 3, 2, 1]
# Using list.reversed() to reverse a list in Python
original_list = [1,2,3,4,5,6,7,8,9]
reversed_list = list(reversed(original_list))
print(reversed_list)
(OR)
original_list = [1,2,3,4,5,6,7,8,9]
print(type(reversed(original_list)))
# Reverse a Python list with list indexing
original_list = [1,2,3,4,5,6,7,8,9]
reversed_list = original_list[::-1]
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# Reverse a Python list with a for loop
● Define two lists, our original list and an empty list to store our reversed items
● Then loop over each item in the list. We reassign the reversed list to a list
containing each item plus the reversed list.
original_list = [1,2,3,4,5,6,7,8,9]
reversed_list = list()
for item in original_list:
reversed_list = [item] + reversed_list
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# Reverse a Python list with a List Comprehension
● Create a variable start that represents the length of the list minus one
● Then create a list comprehension that accesses each index item in our list using
the range from the start position to 0 in reverse order.
original_list = [1,2,3,4,5,6,7,8,9]
start = len(original_list) - 1
reversed_list = [original_list[i] for i in range(start, -1, -1)]
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# Reverse a Python list with slice()
Python also provides a slice() function that allows us to index an object in the same way
that the list indexing method works above.
original_list = [1,2,3,4,5,6,7,8,9]
reverser = slice(None, None, -1)
reversed_list = original_list[reverser]
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Solution:
list1 = []
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
ele= int(input("Enter elements: "))
list1.append(ele)
print("Smallest element is:", min(list1))
Output:
Enter number of elements in list: 4
Enter elements: 12
Enter elements: 19
Enter elements: 11
Enter elements: 99
Smallest element is: 11
Solution:
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
deduplicated_list = list()
for item in duplicated_list:
if item not in deduplicated_list:
deduplicated_list.append(item)
print(deduplicated_list)
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
deduplicated_list = list()
[deduplicated_list.append(item) for item in duplicated_list if item not in deduplicated_list]
print(deduplicated_list)
Solution:
#Method-1
sample_list = ['datagy', 4, 100.0]
print('First item: ',sample_list[0])
print('Last item: ',sample_list[-1])
#Method-2 Append to Lists in Python, The append() method adds a single item to the
end of an existing list in Python. The method takes a single parameter and adds it to the
end. The added item can include numbers, strings, lists, or dictionaries. Let’s try this out
with a number of examples.
sample_list = [1,2,3]
sample_list.append(4)
print(sample_list)
[1, 2, 3, 4]
Appending to List to a List
sample_list = [1,2,3]
sample_list2 = [4,5,6]
sample_list.append(sample_list2)
print(sample_list)
[1, 2, 3, [4, 5, 6]]
#Printing 4th Item from the list
print(sample_list[3])
[4, 5, 6]
#Mehotd-3: We can also insert items using a negative index. The index of -1
would insert the item in the second last spot:
sample_list = [1,2,3,4,5,6]
sample_list.insert(-1,99)
print(sample_list)
[1, 2, 3, 4, 5, 99, 6]
sample_list = [1,2,3]
sample_list2 = [4,5,6]
sample_list.extend(sample_list2)
print(sample_list)
[1, 2, 3, 4, 5, 6]
5. Write a python script to count the number of strings in a list where the
string length is 2 or more?
Solution:
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
MODULE 2: Exercise Programs on Tuples.
Solution:
output:
Solution:
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
count = tuplex.count(4)
print(count)
Solution:
#A new empty set
color_set = set()
print(color_set)
print("\nAdd single element:")
color_set.add("Red")
print(color_set)
print("\nAdd multiple items:")
color_set.update(["Blue", "Green"])
print(color_set)
output:
Solution:
#Union Operation
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
setc = setc1.union(setc2)
print("\nUnion of above sets:")
print(setc)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
print("\nUnion of above sets:")
setn = setn1.union(setn2)
print(setn)
#Intersection
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
print("Original set elements:")
print(setx)
print(sety)
print("\nIntersection of two said sets:")
setz = setx & sety
print(setz)
#Difference
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
r1 = setc1.difference(setc2)
print("\nDifference of setc1 - setc2:")
print(r1)
r2 = setc2.difference(setc1)
print("\nDifference of setc2 - setc1:")
print(r2)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
r1 = setn1.difference(setn2)
print("\nDifference of setn1 - setn2:")
print(r1)
r2 = setn2.difference(setn1)
print("\nDifference of setn2 - setn1:")
print(r2)
#Symmetric
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
r1 = setc1.symmetric_difference(setc2)
print("\nSymmetric difference of setc1 - setc2:")
print(r1)
r2 = setc2.symmetric_difference(setc1)
print("\nSymmetric difference of setc2 - setc1:")
print(r2)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
r1 = setn1.symmetric_difference(setn2)
print("\nSymmetric difference of setn1 - setn2:")
print(r1)
r2 = setn2.symmetric_difference(setn1)
print("\nSymmetric difference of setn2 - setn1:")
print(r2)
Solution:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)
5. Write a Python Script to check whether a given key already exists or not
in a dictionary?
Solution:
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
Sample Dictionary:
dict1={1:10,2:20}
dict2={3:30,4:40}
dict3={{5:50,6:60}
The result must be: {1:10,2:20,3:30, 4:40, 5:50, 6:60}
Solution:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)
7. Write a Python Script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are squares of keys?
Solution:
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Solution:
keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
MODULE 4: Exercise Programs on functions and recursion
Solution:
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
2. Write a program which make sure of function to display all such numbers
which are divisible by 7 but are not a multiple of 5, between given range
X and Y
Solution:
nl=[]
for x in range(1500, 2701):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print (','.join(nl))
3. Define a function to find mean, medium, mode for the given numbers in
a list?
Solution:
# Python program to print mean of elements
# list of elements to calculate mean
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
print("Mean / Average is: " + str(mean))
# Python program to print median of elements
# list of elements to calculate median
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
n_num.sort()
if n % 2 == 0:
median1 = n_num[n//2]
median2 = n_num[n//2 - 1]
median = (median1 + median2)/2
else:
median = n_num[n//2]
print("Median is: " + str(median))
# Python program to print mode of elements from collections import Counter
from collections import Counter
# list of elements to calculate mode
n_num = [1, 2, 3, 4, 5, 5]
n = len(n_num)
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
if len(mode) == n:
get_mode = "No mode found"
else:
get_mode = "Mode is / are: " + ', '.join(map(str, mode))
print(get_mode)
Solution:
def test(n):
a = [1, 1]
while len(a) < n: a += [sum(a[-2:])]
return a[:n]
n = 10
print("\nFind the first",n,"Fibonacci numbers:")
print(test(n))
n = 15
print("\nFind the first",n,"Fibonacci numbers:")
print(test(n))
n = 50
print("\nFind the first",n,"Fibonacci numbers:")
print(test(n))
Solution:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factorial : "))
print(factorial(n))
Solution:
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print("GCD of 12 & 17 =",gcd(12, 17))
print("GCD of 4 & 6 =",gcd(4, 6))
print("GCD of 336 & 360 =",gcd(336, 360))
MODULE 5: Exercise programs on Date and Time Modules
Solution:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Solution:
import time
milli_sec = int(round(time.time() * 1000))
print(milli_sec)
3. Write a python script to print, the next 5 days starting from today?
Solution:
import datetime
base = datetime.datetime.today()
for x in range(0, 5):
print(base + datetime.timedelta(days=x))
Solution:
# Python program to handle simple runtime error
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Solution:
# Python catch multiple exceptions
try:
# defining variables
a = 10
b= 0
c = "abc"
# adding the variables
d =a+c
# Zerodivision error
except ZeroDivisionError:
# printing error
print("Zero Division Error occurs")
# index error
except IndexError:
# printing
print("Index error occurs")
# type error
except TypeError:
# printing
print("Type error occurs")
MODULE 7: Exercise programs on Strings
Solution:
str1 = "welcome to all student"
capital = str1.upper()
print(capital)
str2 = "MADANAPALLE INSTITUTE OF TECHNOLOGY AND SCIENCE is an engineering
college"
lower = str2.lower()
print(lower)
str3 = str2.replace("MADANAPALLE INSTITUTE OF TECHNOLOGY AND SCIENCE","MITS")
print(str3)
str4 = " This is an example of strip "
left = str4.strip()
print(left)
str1 = "welcome to all student"
prefix1 = str1.startswith('hellow')
print(prefix1)
prefix2 = str1.startswith('wel')
print(prefix2)
prefix3 = str1.endswith('student')
print(prefix3)
Solution:
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
3. Implement a Python Script to accept lines of text and find the number of
characters, number of vowels and number of blank spaces in it?
Solution:
# Python program to count number of characters, vowels, blank spaces
def counting(filename):
# Opening the file in read mode
txt_file = open(filename, "r")
# Initialize three variables to count number of characters, vowels,lines and blank
spaces respectively
vowel = 0
character = 0
blankspaces = 0
# Make a vowels list so that we can check whether the character is vowel or not
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
# Iterate over the characters present in file
for alpha in txt_file.read():
# Checking if the current character is not vowel or new line character
elif alpha not in vowels_list and alpha != "\n":
character += 1
4. Implement a python script that takes a list of words and returns the
length of the longest one.
Solution:
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
result = find_longest_word(["PHP", "Exercises", "Backend"])
print("\nLongest word: ",result[1])
print("Length of the longest word: ",result[0])
Module 8: Exercise programs on Regular Expressions
1. Write a Python script to check that a string contains only a certain set of
characters (in this case a-z, A-Z and 0-9).
Solution:
import re
def is_allowed_specific_char(string):
charRe = re.compile(r'[^a-zA-Z0-9]')
string = charRe.search(string)
return not bool(string)
print(is_allowed_specific_char("ABCDEFabcdef123450"))
print(is_allowed_specific_char("*&%@#!}{"))
Solution:
l, u, p, d = 0, 0, 0, 0
print(“Enter Input String”)
s=input()
capitalalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
smallalphabets="abcdefghijklmnopqrstuvwxyz"
specialchar="$@_"
digits="0123456789"
if (len(s) >= 8):
for i in s:
# counting lowercase alphabets
if (i in smallalphabets):
l+=1
# counting uppercase alphabets
if (i in capitalalphabets):
u+=1
# counting digits
if (i in digits):
d+=1
# counting the mentioned special characters
if(i in specialchar):
p+=1
if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):
print("Valid Password")
else:
print("Invalid Password")
Solution:
from re import sub
def snake_case(s):
return '-'.join(
sub(r"(\s|_|-)+"," ",
sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: ' ' + mo.group(0).lower(), s)).split())
print(snake_case('JavaScript'))
print(snake_case('GDScript'))
print(snake_case('BTW...what *do* you call that naming style? snake_case? '))
4. Write a Python program that reads a given expression and evaluates it.
Solution:
import re
print("Input number of data sets:")
class c(int):
def __add__(self,n):
return c(int(self)+int(n))
def __sub__(self,n):
return c(int(self)-int(n))
def __mul__(self,n):
return c(int(self)*int(n))
def __truediv__(self,n):
return c(int(int(self)/int(n)))
for _ in range(int(input())):
print("Input an expression:")
print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))
Module 9: Exercise programs on Object Oriented Programming
1. Write a Python script to create and access class variables and methods.
Solution:
# Program to demonstrate 'Variable
# defined outside the class'
# Variable defined outside the class.
outVar = 'outside_class'
print("Outside_class1", outVar)
''' Class one '''
class Geek:
print("Outside_class2", outVar)
def access_method(self):
print("Outside_class3", outVar)
# Calling method by creating object
uac = Geek()
uac.access_method()
''' Class two '''
class Another_Geek_class:
print("Outside_class4", outVar)
def another_access_method(self):
print("Outside_class5", outVar)
# Calling method by creating object
uaac = Another_Geek_class()
uaac.another_access_method()
Solution:
class Mathematics:
def add(self, *args):
sum = 0
for a in args:
sum = sum + a
print(sum)
obj = Mathematics()
obj.add(8, 9, 12)
obj.add(8, 9)
1. Implement Python Script for checking the given year is leap year or not
Solution:
# Python program to check the given year is leap or not using if else
n = input("Please enter year")
year = int (n)
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
Output:
Please enter year 2021
2021 is Not the Leap Year
# Python program to check the given year is leap or not using elif
if (year%400 == 0):
print("%d is a Leap Year" %year)
elif (year%100 == 0):
print("%d is Not the Leap Year" %year)
elif (year%4 == 0):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
Output:
Please enter year 2020
2020 is a leap year
# Python program to check the given year is leap or not using nested if
statement
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:
Please enter year 2020
2020 is a leap year
# Python program to check the given year is leap or not using function
# using math calender module in Python
if val == True:
print("% s is a Leap Year" % year)
else:
print("% s is not a Leap Year" % year)
Output:
Please enter year 2019
2019 is not a Leap Year
Solution:
lst = []
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
Solution
Output = 0
def revNum(Num):
global Output
if(Num > 0):
Reminder = Num %10
Output = (Output *10) + Reminder
revNum(Num //10)
return Output
Output = revNum(Num)
Solution:
Verifying for 3 digit numbers
# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:
Enter a number: 663
663 is not an Armstrong number
#Verifying for n digits
num=int(input("Enter a number: "))
# Changed num variable to string and calculated the length (number of digits)
order = len(str(num))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:
Solution:
The sum of natural numbers formula is used to find the sum of the natural numbers up to
n terms. i.e., 1 + 2 + 3 + 4 + 5 + …. up to n terms. To derive the formula, we need to
use the sum of the arithmetic progression formula, because the natural numbers are
arranged in an arithmetic sequence. With 1 as the first term, 1 as the common
difference, and up to n terms, we use the sum of an AP = n/2(2+(n-1)). Solving this, you
get the sum of natural numbers formula = [n(n+1)]/2.
Sum of Natural Numbers Formula = [n(n+1)]/2 .
Python Program to Calculate Sum of N Natural Numbers using While Loop
Follow the below steps and write a program to find the sum of first n natural numbers
using while loop in python:
total = 0
value = 1
Solution:
A Palindrome in python if it remained the same when reversed. i.e., 252 is a palindrome
number because this number remains the same after reversing it.
Python Palindrome Program using While Loop
reverse = 0
def integer_reverse(number):
global reverse
rev = integer_reverse(number)
if(number == rev):
print("The %d is a Palindrome Number" %number)
else:
print("The %d is not a Palindrome Number" %number)
Output:
1
2
Please Enter any Number: 151
The 151 is a Palindrome Number
Solution:
“Factors” are the numbers you multiply to get another number. For instance, factors of
15 are 3 and 5, because 3×5 = 15. Some numbers have more than one factorization
(more than one way of being factored). For instance, 12 can be factored as 1×12, 2×6,
or 3×4.
Python Program to Find the Factors of a Number using For Loop
for i in range(1,num+1):
if num % i == 0:
print(i)
Output:
Enter a number: 10
The factors of 10 are,
1
2
5
10
Python Program to Find the Factors of a Number by using Functions
print_factors(num)
Output:
Enter a number: 10
The factors of 10 are,
1
2
5
10
8. Implement Python Script to print all prime numbers within the given range
Solution:
Output:
Please Enter any Number: 25
Prime numbers between 1 and 25 are:
2 3 5 7 11 13 17 19 23
Python Program To Print Numbers From 1 to N Using While Loop
# Python Program to print Prime Numbers from 1 to N
Number = 1
sum = 0
i=2
Output:
Find sum of prime numbers upto : 25
Sum of all prime numbers upto 25 : 98
Solution:
# python program to find the sum of series: 1 + x² + x³ + ... + xⁿ
*
* *
* * *
* * * *
* * * * *
Solution:
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
Output:
*
* *
* * *
* * * *
* * * * *
MODULE I: Exercise Programs on Python Lists
Solution:
# Using list.reverse() to reverse a list in Python
values = [1, 2, 3, 4, 5]
values.reverse()
print(values)
Output: [5, 4, 3, 2, 1]
# Using list.reversed() to reverse a list in Python
original_list = [1,2,3,4,5,6,7,8,9]
reversed_list = list(reversed(original_list))
print(reversed_list)
(OR)
original_list = [1,2,3,4,5,6,7,8,9]
print(type(reversed(original_list)))
# Reverse a Python list with list indexing
original_list = [1,2,3,4,5,6,7,8,9]
reversed_list = original_list[::-1]
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# Reverse a Python list with a for loop
● Define two lists, our original list and an empty list to store our reversed items
● Then loop over each item in the list. We reassign the reversed list to a list
containing each item plus the reversed list.
original_list = [1,2,3,4,5,6,7,8,9]
reversed_list = list()
for item in original_list:
reversed_list = [item] + reversed_list
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# Reverse a Python list with a List Comprehension
● Create a variable start that represents the length of the list minus one
● Then create a list comprehension that accesses each index item in our list using
the range from the start position to 0 in reverse order.
original_list = [1,2,3,4,5,6,7,8,9]
start = len(original_list) - 1
reversed_list = [original_list[i] for i in range(start, -1, -1)]
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# Reverse a Python list with slice()
Python also provides a slice() function that allows us to index an object in the same way
that the list indexing method works above.
original_list = [1,2,3,4,5,6,7,8,9]
reverser = slice(None, None, -1)
reversed_list = original_list[reverser]
print(reversed_list)
Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Solution:
# Python program to find smallest number in a list
# creating empty list
list1 = []
# asking number of elements to put in list
num = int(input("Enter number of elements in list: "))
# iterating till num to append elements in list
for i in range(1, num + 1):
ele= int(input("Enter elements: "))
list1.append(ele)
Solution:
# Remove Duplicates from a Python list using a For Loop
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
deduplicated_list = list()
for item in duplicated_list:
if item not in deduplicated_list:
deduplicated_list.append(item)
print(deduplicated_list)
# Remove Duplicates from a Python list using a List Comprehension
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
deduplicated_list = list()
[deduplicated_list.append(item) for item in duplicated_list if item not in deduplicated_list]
print(deduplicated_list)
# Remove Duplicates from a Python list using a collections
from collections import OrderedDict
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
deduplicated_list = list(OrderedDict.fromkeys(duplicated_list))
print(deduplicated_list)
Output: [1, 2, 3, 4]
Solution:
#Method-1
sample_list = ['datagy', 4, 100.0]
print('First item: ',sample_list[0])
print('Last item: ',sample_list[-1])
#Method-2 Append to Lists in Python, The append() method adds a single item to the
end of an existing list in Python. The method takes a single parameter and adds it to the
end. The added item can include numbers, strings, lists, or dictionaries. Let’s try this out
with a number of examples.
sample_list = [1,2,3]
sample_list.append(4)
print(sample_list)
[1, 2, 3, 4]
Appending to List to a List
sample_list = [1,2,3]
sample_list2 = [4,5,6]
sample_list.append(sample_list2)
print(sample_list)
[1, 2, 3, [4, 5, 6]]
#Printing 4th Item from the list
print(sample_list[3])
[4, 5, 6]
#Mehotd-3: We can also insert items using a negative index. The index of -1 would insert
the item in the second last spot:
sample_list = [1,2,3,4,5,6]
sample_list.insert(-1,99)
print(sample_list)
[1, 2, 3, 4, 5, 99, 6]
#Method-4: Extend List in Python, using the Extend() method.
sample_list = [1,2,3]
sample_list2 = [4,5,6]
sample_list.extend(sample_list2)
print(sample_list)
[1, 2, 3, 4, 5, 6]
#Method-5: Concatenate List in Python
sample_list = [1,2,3]
sample_list2 = [4,5,6]
sample_list = sample_list + sample_list2
print(sample_list)
Output: [1, 2, 3, 4, 5, 6]
5. Write a python script to count the number of strings in a list where the
string length is 2 or more?
Solution:
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
MODULE 2: Exercise Programs on Tuples.
Solution:
#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)
Solution:
#create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4)
print(count)
Solution:
#A new empty set
color_set = set()
print(color_set)
print("\nAdd single element:")
color_set.add("Red")
print(color_set)
print("\nAdd multiple items:")
color_set.update(["Blue", "Green"])
print(color_set)
Solution:
#Union Operation
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
setc = setc1.union(setc2)
print("\nUnion of above sets:")
print(setc)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
print("\nUnion of above sets:")
setn = setn1.union(setn2)
print(setn)
#Intersection
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
print("Original set elements:")
print(setx)
print(sety)
print("\nIntersection of two said sets:")
setz = setx & sety
print(setz)
#Difference
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
r1 = setc1.difference(setc2)
print("\nDifference of setc1 - setc2:")
print(r1)
r2 = setc2.difference(setc1)
print("\nDifference of setc2 - setc1:")
print(r2)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
r1 = setn1.difference(setn2)
print("\nDifference of setn1 - setn2:")
print(r1)
r2 = setn2.difference(setn1)
print("\nDifference of setn2 - setn1:")
print(r2)
#Symmetric
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
r1 = setc1.symmetric_difference(setc2)
print("\nSymmetric difference of setc1 - setc2:")
print(r1)
r2 = setc2.symmetric_difference(setc1)
print("\nSymmetric difference of setc2 - setc1:")
print(r2)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
r1 = setn1.symmetric_difference(setn2)
print("\nSymmetric difference of setn1 - setn2:")
print(r1)
r2 = setn2.symmetric_difference(setn1)
print("\nSymmetric difference of setn2 - setn1:")
print(r2)
Solution:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)
5. Write a Python Script to check whether a given key already exists or not
in a dictionary?
Solution:
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
Sample Dictionary:
dict1={1:10,2:20}
dict2={3:30,4:40}
dict3={{5:50,6:60}
The result must be: {1:10,2:20,3:30, 4:40, 5:50, 6:60}
Solution:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)
7. Write a Python Script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are squares of keys?
Solution:
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Solution:
keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
MODULE 4: Exercise Programs on functions and recursion
Solution:
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
2. Write a program which make sure of function to display all such numbers
which are divisible by 7 but are not a multiple of 5, between given range
X and Y
Solution:
nl=[]
for x in range(1500, 2701):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print (','.join(nl))
3. Define a function to find mean, medium, mode for the given numbers in
a list?
Solution:
# Python program to print mean of elements
# list of elements to calculate mean
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
print("Mean / Average is: " + str(mean))
# Python program to print median of elements
# list of elements to calculate median
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
n_num.sort()
if n % 2 == 0:
median1 = n_num[n//2]
median2 = n_num[n//2 - 1]
median = (median1 + median2)/2
else:
median = n_num[n//2]
print("Median is: " + str(median))
# Python program to print mode of elements from collections import Counter
from collections import Counter
# list of elements to calculate mode
n_num = [1, 2, 3, 4, 5, 5]
n = len(n_num)
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
if len(mode) == n:
get_mode = "No mode found"
else:
get_mode = "Mode is / are: " + ', '.join(map(str, mode))
print(get_mode)
Solution:
def test(n):
a = [1, 1]
while len(a) < n: a += [sum(a[-2:])]
return a[:n]
n = 10
print("\nFind the first",n,"Fibonacci numbers:")
print(test(n))
n = 15
print("\nFind the first",n,"Fibonacci numbers:")
print(test(n))
n = 50
print("\nFind the first",n,"Fibonacci numbers:")
print(test(n))
Solution:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factorial : "))
print(factorial(n))
Solution:
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print("GCD of 12 & 17 =",gcd(12, 17))
print("GCD of 4 & 6 =",gcd(4, 6))
print("GCD of 336 & 360 =",gcd(336, 360))
MODULE 5: Exercise programs on Date and Time Modules
Solution:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Solution:
import time
milli_sec = int(round(time.time() * 1000))
print(milli_sec)
3. Write a python script to print, the next 5 days starting from today?
Solution:
import datetime
base = datetime.datetime.today()
for x in range(0, 5):
print(base + datetime.timedelta(days=x))
Solution:
# Python program to handle simple runtime error
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Solution:
# Python catch multiple exceptions
try:
# defining variables
a = 10
b= 0
c = "abc"
# adding the variables
d =a+c
# Zerodivision error
except ZeroDivisionError:
# printing error
print("Zero Division Error occurs")
# index error
except IndexError:
# printing
print("Index error occurs")
# type error
except TypeError:
# printing
print("Type error occurs")
MODULE 7: Exercise programs on Strings
Solution:
str1 = "welcome to all student"
capital = str1.upper()
print(capital)
str2 = "MADANAPALLE INSTITUTE OF TECHNOLOGY AND SCIENCE is an engineering
college"
lower = str2.lower()
print(lower)
str3 = str2.replace("MADANAPALLE INSTITUTE OF TECHNOLOGY AND SCIENCE","MITS")
print(str3)
str4 = " This is an example of strip "
left = str4.strip()
print(left)
str1 = "welcome to all student"
prefix1 = str1.startswith('hellow')
print(prefix1)
prefix2 = str1.startswith('wel')
print(prefix2)
prefix3 = str1.endswith('student')
print(prefix3)
Solution:
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
3. Implement a Python Script to accept lines of text and find the number of
characters, number of vowels and number of blank spaces in it?
Solution:
# Python program to count number of characters, vowels, blank spaces
def counting(filename):
# Opening the file in read mode
txt_file = open(filename, "r")
# Initialize three variables to count number of characters, vowels,lines and blank
spaces respectively
vowel = 0
character = 0
blankspaces = 0
# Make a vowels list so that we can check whether the character is vowel or not
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
# Iterate over the characters present in file
for alpha in txt_file.read():
# Checking if the current character is not vowel or new line character
elif alpha not in vowels_list and alpha != "\n":
character += 1
4. Implement a python script that takes a list of words and returns the
length of the longest one.
Solution:
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
result = find_longest_word(["PHP", "Exercises", "Backend"])
print("\nLongest word: ",result[1])
print("Length of the longest word: ",result[0])
Module 8: Exercise programs on Regular Expressions
1. Write a Python script to check that a string contains only a certain set of
characters (in this case a-z, A-Z and 0-9).
Solution:
import re
def is_allowed_specific_char(string):
charRe = re.compile(r'[^a-zA-Z0-9]')
string = charRe.search(string)
return not bool(string)
print(is_allowed_specific_char("ABCDEFabcdef123450"))
print(is_allowed_specific_char("*&%@#!}{"))
Solution:
l, u, p, d = 0, 0, 0, 0
print(“Enter Input String”)
s=input()
capitalalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
smallalphabets="abcdefghijklmnopqrstuvwxyz"
specialchar="$@_"
digits="0123456789"
if (len(s) >= 8):
for i in s:
# counting lowercase alphabets
if (i in smallalphabets):
l+=1
# counting uppercase alphabets
if (i in capitalalphabets):
u+=1
# counting digits
if (i in digits):
d+=1
# counting the mentioned special characters
if(i in specialchar):
p+=1
if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):
print("Valid Password")
else:
print("Invalid Password")
Solution:
from re import sub
def snake_case(s):
return '-'.join(
sub(r"(\s|_|-)+"," ",
sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: ' ' + mo.group(0).lower(), s)).split())
print(snake_case('JavaScript'))
print(snake_case('GDScript'))
print(snake_case('BTW...what *do* you call that naming style? snake_case? '))
4. Write a Python program that reads a given expression and evaluates it.
Solution:
import re
print("Input number of data sets:")
class c(int):
def __add__(self,n):
return c(int(self)+int(n))
def __sub__(self,n):
return c(int(self)-int(n))
def __mul__(self,n):
return c(int(self)*int(n))
def __truediv__(self,n):
return c(int(int(self)/int(n)))
for _ in range(int(input())):
print("Input an expression:")
print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))
Module 9: Exercise programs on Object Oriented Programming
1. Write a Python script to create and access class variables and methods.
Solution:
# Program to demonstrate 'Variable
# defined outside the class'
# Variable defined outside the class.
outVar = 'outside_class'
print("Outside_class1", outVar)
''' Class one '''
class Geek:
print("Outside_class2", outVar)
def access_method(self):
print("Outside_class3", outVar)
# Calling method by creating object
uac = Geek()
uac.access_method()
''' Class two '''
class Another_Geek_class:
print("Outside_class4", outVar)
def another_access_method(self):
print("Outside_class5", outVar)
# Calling method by creating object
uaac = Another_Geek_class()
uaac.another_access_method()
Solution:
class Mathematics:
def add(self, *args):
sum = 0
for a in args:
sum = sum + a
print(sum)
obj = Mathematics()
obj.add(8, 9, 12)
obj.add(8, 9)