0% found this document useful (0 votes)
8 views42 pages

21761A5422 Python

The document provides a series of Python scripts that demonstrate various programming concepts, including checking for leap years, finding the largest number among three inputs, reversing numbers, and checking for Armstrong numbers. It also covers calculating the sum of natural numbers, checking for palindromes, finding factors, identifying prime numbers, and summing prime numbers within a range. Additionally, it includes exercises on list manipulation, such as reversing lists, finding minimum and maximum elements, and removing duplicates.

Uploaded by

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

21761A5422 Python

The document provides a series of Python scripts that demonstrate various programming concepts, including checking for leap years, finding the largest number among three inputs, reversing numbers, and checking for Armstrong numbers. It also covers calculating the sum of natural numbers, checking for palindromes, finding factors, identifying prime numbers, and summing prime numbers within a range. Additionally, it includes exercises on list manipulation, such as reversing lists, finding minimum and maximum elements, and removing duplicates.

Uploaded by

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

Introduction: Language Basics and Example Problems (2 Weeks)

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

n = input("Please enter year")

year = int (n)

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:

enter year 2020


2020 is a leap year

Program to check the given year is leap or not using function


import calendar
n = input("Please enter year")
year = int (n)

# calling isleap() method to check for Leap Year


val = calendar.isleap(year)

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

2. Implement Python Script for finding biggest number among 3 numbers

Solution:
lst = []

num = int(input('How many numbers: '))

for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)

print("Maximum element in the list is :", max(lst))


Outpt:
How many numbers: 3
Enter number 4
Enter number 6
Enter number 8
Maximum element in the list is : 8

3. Implement Python Script for for displaying reversal of a number

Solution

num = int(input("Please enter any number: "))

test_num = 0

while(num>0):

remainder = num % 10

test_num = (test_num * 10) + remainder

num = num//10
print("The reverse number is : {}".format(test_num))
Output:
Please enter any number: 221
The reverse number is : 122

Python Program to Reverse a Number using Using Recursion


Num = int(input("Please Enter any Number: ")
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)
print ("Reverse of entered number is = %d" %Output)
Output:

Please Enter any Number: 456


Reverse of entered number is = 654

4. Implement Python Script to check given number is Amstrong or not

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:

Enter a number: 663


663 is not an Armstrong number

#Verifying for n digits


num=int(input("Enter a 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")
Output:

5. Implement Python Script to print sum of N natural numbers

number = int(input("Please Enter any Number: "))


total = 0
value = 1

while (value <= number):


total = total + value
value = value + 1

print("The Sum of Natural Numbers from 1 to {0} = {1}".format(number, total))


Output
Please Enter any Number: 5
The Sum of Natural Numbers from 1 to 5 = 15

Python Program to find Sum of N Natural Numbers using For Loop

number = int(input("Please Enter any Number: "))


total = 0
for value in range(1, number + 1):
total = total + value
print("The Sum of Natural Numbers from 1 to {0} = {1}".format(number, total))
Output:

Please Enter any Number: 10


The Sum of Natural Numbers from 1 to 10 = 55

6. Implement Python Script to check given number is palindrome or not

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

Number = int(input(" Please Enter any Number: "))

print("Prime numbers between", 1, "and", Number, "are:")

for num in range(1, Number + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

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

max = int(input(" Please Enter Any Number: "))

Number = 1

print("Prime numbers between", 1, "and", max, "are:")

while(Number <= max):


count = 0
i=2

while(i <= Number//2):


if(Number % i == 0):
count = count + 1
break
i=i+1

if (count == 0 and Number != 1):


print(" %d" %Number, end = ' ')
Number = Number + 1
Output:
Please Enter Any Number: 15
Prime numbers between 1 and 15 are:
2 3 5 7 11 13

Python program to find sum of all prime numbers between 1 to n


# Python Program to print n prime number using for loop

max = int(input("Find sum of prime numbers upto : "))

sum = 0

for num in range(2, max + 1):

i=2

for i in range(2, num):


if (int(num % i) == 0):
i = num
break;

#If the number is prime then add it.


if i is not num:
sum += num

print("\nSum of all prime numbers upto", max, ":", sum)


Output:
Find sum of prime numbers upto : 25
Sum of all prime numbers upto 25 : 98

9. Implement Python Script to calculate the series: S=1+x+x2+x3+..... xn

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)

10. Implement Python Script to print the following pattern:

*
* *
* * *
* * * *
* * * * *
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

1. Write a python script to display elements of a list in reverse order?

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]

2. Write a Python script to find the minimum and maximum elements


without using built-in operations in the lists?

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

3. Write a python script to remove duplicate elements from a list?

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)

# 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]

4. Write a python script to append a list to the second 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]

#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.

1. Write a python script to create a tuple with different data types?

Solution:

tuplex = ("tuple", False, 3.2, 1)


print(tuplex)

output:

2. Write a python script to find repeated items of a tuple?

Solution:
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
count = tuplex.count(4)
print(count)

3. Write a python script to replace the last value of tuples in a list.

Sample list: [(10,20,40), (40,50,60),(70,80,90)]


Expected output: [(10,20,100),(40,50,100),(70,80,100)]
Solution:
l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (100,) for t in l])

4. Write a python script to sort a tuple by its float element?


Sample data: [(‘item1’,’12.20’), (‘item2’,’15.10’),(‘item3’,’24.5’)]
Solution:
price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
print( sorted(price, key=lambda x: float(x[1]), reverse=True))
output:

MODULE 3: Exercise Programs on Sets and Dictionaries

1. Write a Python script to add member(s) in a Set.

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:

2. Write a Python Script to perform Union, Intersection, difference and


symmetric differences of given two sets.

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)

3. Write a Python Script to test whether every element in S is in T and


every element in T is in S?
4. Write a Python Script to sort (Ascending and Descending) a dictionary by
value?

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)

6. Write a Python Script to concatenate following dictionaries to create a


new one:

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)

8. Write a Python Script to map two lists into a dictionary?

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

1. Define a function max_of_three() that takes 3 numbers as arguments and


returns the largest of them?

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)

4. Define a function which generates Fibonacci series up to n numbers

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))

5. Implement a python script for factorial of number by using recursion?

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))

6. Implement a python script to find GCD of given two numbers using


recursion?

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

1. Write a python script to get the current time in python?

Solution:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

2. Write a python script to get current time in milliseconds in Python?

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))

MODULE 6: Exercise programs to Exception Handling

1. Write a python script to handle simple errors by using exception


handling mechanism?

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")

2. Write a Python Script to handle multiple errors with one exception


statement?

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

1. Implement python script to perform various operations on string using


string libraries

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)

2. Implement a Python script to check if a given string is palindrome or


not?

Solution:
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1

while right_pos >= left_pos:


if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))

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

# Checking if the current character is vowel or not


if alpha in vowels_list:
vowel += 1

# Checking if the current character is new line character or not


elif alpha == "\n":
line += 1
if(i !=" " and i !="\n"):
# incrementing character count by 1
num_charc += 1
# Print the desired output on the console.

print("Number of vowels in ", filename, " = ", vowel)


print("Number of characters in ", filename, " = ", character)
print('Number of spaces in text file: ', blankspaces)
# Calling the function counting which gives the desired output
counting('Myfile.txt')

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("*&%@#!}{"))

2. Write a Python script to check whether a password is valid or not.

Conditions for a valid password are:

1. Should have at least one number.


2. Should have at least one uppercase and one lowercase character.
3. Should have at least one special symbol.
4. Should be between 6 to 20 characters long.

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")

3. Write a Python program to convert a given string to a snake case.

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.

Terms and conditions:

5. The expression consists of numerical values, operators and parentheses,


and ends with '='.
6. The operators includes +, -, *, / where, represents, addition, subtraction,
multiplication and division.
7. When two operators have the same precedence, they are applied from left
to right.
8. You may assume that there is no division by zero.
9. All calculation is performed as integers, and after the decimal point should
be truncated Length of the expression will not exceed 100.
10. -1 ? 10 9 = intermediate results of computation = 10 9

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()

2. Write a Python script to implement method overloading.

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)

Introduction: Language Basics and Example Problems (2 Weeks)

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

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:
Please enter year 2020
2020 is a leap year
# Python program to check the given year is leap or not using nested if
statement

n = input("Please enter year")

year = int (n)

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

#here import calender module


import calendar

n = input("Please enter year")

year = int (n)

# calling isleap() method to check for Leap Year


val = calendar.isleap(year)

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

2. Implement Python Script for finding biggest number among 3 numbers

Solution:
lst = []

num = int(input('How many numbers: '))

for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)

print("Maximum element in the list is :", max(lst))


Outpt:
How many numbers: 3
Enter number 4
Enter number 6
Enter number 8
Maximum element in the list is : 8

3. Implement Python Script for for displaying reversal of a number

Solution

1. Take input from the user in the program.


2. Define 0 to the variable “test_num”.
3. Check whether the given number is greater than zero using a while loop.
4. If yes, find the remainder by performing modulus of 10 with the input.
5. Multiply test_num by 10 and add the remainder to it, store the answer in rev.
6. Get the quotient of the input.
7. The loop will repeat until the number is reversed.
8. Print Reverse a number

# Get input from the user


num = int(input("Please enter any number: "))

# Initiate value to null


test_num = 0

# iterate number using while loop


while(num>0):
#Logic to reverse a number
remainder = num % 10
test_num = (test_num * 10) + remainder
num = num//10

# print the result


print("The reverse number is : {}".format(test_num))
Output:
Please enter any number: 123
The reverse number is : 321
Python Program to Reverse a Number using Using Recursion

1. Take input from the user in the program.


2. Define 0 to the variable “output”.
3. Define function and Implement logic to reverse a number
4. Check whether the given number is greater than zero using a while loop.
5. If yes, find the remainder by performing modulus of 10 with the input.
6. Multiply test_num by 10 and add the remainder to it, store the answer in rev.
7. Get the quotient of the input.
8. The loop will repeat until the number is reversed.
9. Call Function, which is defined above.
10. Print Reverse a number.

# Get input from user


Num = int(input("Please Enter any Number: "))

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)

print("Reverse of entered number is = %d" %Output)


Output:
Please Enter any Number: 456
Reverse of entered number is = 654

4. Implement Python Script to check given number is Amstrong or not

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:

5. Implement Python Script to print sum of N natural numbers

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:

1. Take input number from the user


2. Iterate while loop and calculate sum of n natural number
3. As well as store value in variable
4. Print sum of n natural number

# Python Program to find Sum of N Natural Numbers

number = int(input("Please Enter any Number: "))

total = 0
value = 1

while (value <= number):


total = total + value
value = value + 1

print("The Sum of Natural Numbers from 1 to {0} = {1}".format(number, total))


Output
Please Enter any Number: 5
The Sum of Natural Numbers from 1 to 5 = 15
Python Program to find Sum of N Natural Numbers using For Loop
Follow the below steps and write a program to find the sum of first n natural numbers
using for loop in python:

1. Take input number from the user


2. Iterate for loop and calculate sum of n natural number
3. As well as store value in variable
4. Print sum of n natural number

# Python Program to find Sum of N Natural Numbers

number = int(input("Please Enter any Number: "))


total = 0

for value in range(1, number + 1):


total = total + value

print("The Sum of Natural Numbers from 1 to {0} = {1}".format(number, total))


Output:
Please Enter any Number: 10
The Sum of Natural Numbers from 1 to 10 = 55

6. Implement Python Script to check given number is palindrome or not

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

1. Take an input number from the user.


2. Reverse a given number using while loop
3. Compare the original number with the reverse number.
4. If both numbers exactly match, then it is a Python Palindrome number. Otherwise,
it is not a Palindrome number.

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!
Palindrome Program in Python using Function

1. Take an input number from the user.


2. Reverse a given number using function
3. Compare the original number with the reverse number.
4. If both numbers exactly match, then it is a Python Palindrome number. Otherwise,
it is not a Palindrome number.

# Python Palindrome Program using Functions

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:
“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

1. Take input number from user


2. Iterate For Loop over every number from 1 to the given number
3. If the loop iterator evenly divides the provided number i.e. number % i == 0 print
it.
4. Print Result

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

1. Create Function, which is calculate factors of number


2. Take input number from user
3. Call Function
4. Print Result

# Python Program to find the factors of a number

# This function computes the factor of the argument passed


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:

1. Python Program to find Prime Number using For Loop


2. Python Program To Print Numbers From 1 to N Using For Loop
3. Python Program To Print Numbers From 1 to N Using While Loop
4. Python program to find sum of all prime numbers between 1 to n

#Python 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

Number = int(input(" Please Enter any Number: "))

print("Prime numbers between", 1, "and", Number, "are:")

for num in range(1, Number + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

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

max = int(input(" Please Enter Any Number: "))

Number = 1

print("Prime numbers between", 1, "and", max, "are:")

while(Number <= max):


count = 0
i=2

while(i <= Number//2):


if(Number % i == 0):
count = count + 1
break
i=i+1

if (count == 0 and Number != 1):


print(" %d" %Number, end = ' ')
Number = Number + 1
Output:
Please Enter Any Number: 15
Prime numbers between 1 and 15 are:
2 3 5 7 11 13

Python program to find sum of all prime numbers between 1 to n


# Python Program to print n prime number using for loop

max = int(input("Find sum of prime numbers upto : "))

sum = 0

for num in range(2, max + 1):

i=2

for i in range(2, num):


if (int(num % i) == 0):
i = num
break;

#If the number is prime then add it.


if i is not num:
sum += num

print("\nSum of all prime numbers upto", max, ":", sum)

Output:
Find sum of prime numbers upto : 25
Sum of all prime numbers upto 25 : 98

9. Implement Python Script to calculate the series: S=1+x+x2+x3+..... xn

Solution:
# python program to find the sum of series: 1 + x² + x³ + ... + xⁿ

1. Input the value of x and n from user as integer type


2. define a variable with value of zero to add up till the sum of series, this must be
outside the loop, else each time the loop repeats value will set to zero defeating
the purpose.
3. we use for loop with range of i varying from 0 to n (remember this is not for
infinite series) giving the power of x from 0 to n
4. evey iteration we add x^i to the sum
5. finally print the sum of series

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)

10. Implement Python Script to print the following pattern:

*
* *
* * *
* * * *
* * * * *
Solution:

1. The outermost loop starts from i = 1 to i = row + 1.


2. Among the two inner loops, the for loop prints the required spaces for each row
using formula (rows-i)+1, where rows is the total number of rows and i is the
current row number.
3. The while loop prints the required number stars using formula 2 * i - 1. This
formula gives the number of stars for each row, where row is i.

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

1. Write a python script to display elements of a list in reverse order?

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]

2. Write a Python script to find the minimum and maximum elements


without using built-in operations in the lists?

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)

# print maximum element


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

3. Write a python script to remove duplicate elements from a list?

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]

4. Write a python script to append a list to the second 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]
#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.

1. Write a python script to create a tuple with different data types?

Solution:
#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)

2. Write a python script to find repeated items of a tuple?

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)

3. Write a python script to replace the last value of tuples in a list.


Sample list: [(10,20,40), (40,50,60),(70,80,90)]
Expected output: [(10,20,100),(40,50,100),(70,80,100)]
Solution:
l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (100,) for t in l])

4. Write a python script to sort a tuple by its float element?

Sample data: [(‘item1’,’12.20’), (‘item2’,’15.10’),(‘item3’,’24.5’)]


Solution:
price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
print( sorted(price, key=lambda x: float(x[1]), reverse=True))
MODULE 3: Exercise Programs on Sets and Dictionaries

1. Write a Python script to add member(s) in a Set.

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)

2. Write a Python Script to perform Union, Intersection, difference and


symmetric differences of given two sets.

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)

3. Write a Python Script to test whether every element in S is in T and


every element in T is in S?
4. Write a Python Script to sort (Ascending and Descending) a dictionary by
value?

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)

6. Write a Python Script to concatenate following dictionaries to create a


new one:

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)

8. Write a Python Script to map two lists into a dictionary?

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

1. Define a function max_of_three() that takes 3 numbers as arguments and


returns the largest of them?

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)

4. Define a function which generates Fibonacci series up to n numbers

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))

5. Implement a python script for factorial of number by using recursion?

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))

6. Implement a python script to find GCD of given two numbers using


recursion?

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

1. Write a python script to get the current time in python?

Solution:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

2. Write a python script to get current time in milliseconds in Python?

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))

MODULE 6: Exercise programs to Exception Handling

1. Write a python script to handle simple errors by using exception


handling mechanism?

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")

2. Write a Python Script to handle multiple errors with one exception


statement?

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

1. Implement python script to perform various operations on string using


string libraries

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)

2. Implement a Python script to check if a given string is palindrome or


not?

Solution:
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1

while right_pos >= left_pos:


if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))

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

# Checking if the current character is vowel or not


if alpha in vowels_list:
vowel += 1

# Checking if the current character is new line character or not


elif alpha == "\n":
line += 1
if(i !=" " and i !="\n"):
# incrementing character count by 1
num_charc += 1
# Print the desired output on the console.

print("Number of vowels in ", filename, " = ", vowel)


print("Number of characters in ", filename, " = ", character)
print('Number of spaces in text file: ', blankspaces)
# Calling the function counting which gives the desired output
counting('Myfile.txt')

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("*&%@#!}{"))

2. Write a Python script to check whether a password is valid or not.

Conditions for a valid password are:

1. Should have at least one number.


2. Should have at least one uppercase and one lowercase character.
3. Should have at least one special symbol.
4. Should be between 6 to 20 characters long.

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")

3. Write a Python program to convert a given string to a snake case.

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.

Terms and conditions:

5. The expression consists of numerical values, operators and parentheses,


and ends with '='.
6. The operators includes +, -, *, / where, represents, addition, subtraction,
multiplication and division.
7. When two operators have the same precedence, they are applied from left
to right.
8. You may assume that there is no division by zero.
9. All calculation is performed as integers, and after the decimal point should
be truncated Length of the expression will not exceed 100.
10. -1 ? 10 9 = intermediate results of computation = 10 9

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()

2. Write a Python script to implement method overloading.

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)

You might also like