[go: up one dir, main page]

0% found this document useful (0 votes)
75 views43 pages

Adp Programs

The document provides examples of Python programs that use various operators, control structures, and data types including: 1. Programs that use membership operators to check if an element is in a list, calculate the year a person will turn 100, and find the volume of a cone. 2. Programs that use control structures like if/else statements to count character types in a string, find antonyms from a dictionary, and calculate a series sum. 3. Programs that use lists to print numbers divisible by x but not y, find the sum of odd and even integers, print numbers at odd indices, and remove duplicate elements. 4. Programs that use tuples to find tuples with all
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)
75 views43 pages

Adp Programs

The document provides examples of Python programs that use various operators, control structures, and data types including: 1. Programs that use membership operators to check if an element is in a list, calculate the year a person will turn 100, and find the volume of a cone. 2. Programs that use control structures like if/else statements to count character types in a string, find antonyms from a dictionary, and calculate a series sum. 3. Programs that use lists to print numbers divisible by x but not y, find the sum of odd and even integers, print numbers at odd indices, and remove duplicate elements. 4. Programs that use tuples to find tuples with all
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/ 43

ADP MANUAL

1.Programs on Operators
A) Read a list of numbers and write a program to check whether a particular element is present or not
using membership operators.
Program:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
a=2
if ( a in list ):
print( "Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
Output:
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
ADP MANUAL

b. Read your name and age and write a program to display the year in which you will turn 100 years old

name = input("What is your name: ")


age = int(input("How old are you: "))
year = str((2022 - age)+100)
print(name + " will be 100 years old in the year " + year)

Output
What is your name: Dev
How old are you: 3
Dev will be 100 years old in the year 2119
ADP MANUAL

c. Read radius and height of a cone and write a program to find the volume of a cone.
Program:
height=38
radius=35
pie=3.14285714286
volume=pie*(radius*radius)*height/3
print("volume of the cone="+str(volume))
Output:
volume of the cone= 48766.666666711004
ADP MANUAL

d. Write a program to compute distance between two points taking input from the user (Hint: use
Pythagorean theorem)
Program:

x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)

Output
enter x1 : 8
enter x2 : 6
enter y1 : 9
enter y1 : 5
distance between (8,6) and (9,5) is : 4.47213595
ADP MANUAL

2.PROGRAMS ON CONTROL STRUCTURES


A).Read your email id and write a program to display the no of vowels, consonants, digits and white
spaces in it using if…elif…else statement.

def countCharacterType(str):
vowels = 0
consonant = 0
specialChar = 0
digit = 0
for i in range(0, len(str)):
ch = str[i]
if ( (ch >= 'a' and ch <= 'z') or
(ch >= 'A' and ch <= 'Z') ):
# To handle upper case letters
ch = ch.lower()
if (ch == 'a' or ch == 'e' or ch == 'i'
or ch == 'o' or ch == 'u'):
vowels += 1
else:
consonant += 1
elif (ch >= '0' and ch <= '9'):
digit += 1
else:
specialChar += 1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit)
print("Special Character:", specialChar)
# Driver function.
str = "geeks for geeks121"
countCharacterType(str)
Output:
Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2
ADP MANUAL

B) write a program to create and display dictionary by storing the antonyms of words. find the antonym
of a particular word given by the user from the dictionary using while loop in python
Program
print('enter word from following words ')
no ={'right':'left','up':'down','good':'bad','cool':'hot','east':'west'}
for i in no.keys():
print(i)
y = input()
if y in no :
print('antonym is ', no[y])
else:
print('not in the list given no ')
Output:
enter word from following words
right
up
good
cool
east
ADP MANUAL

C)Write a Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!. (Input :n = 5,
Output : 2.70833)

Program
# Python code to find smallest K-digit
# number divisible by X

def sumofSeries(num):

# Computing MAX
res = 0
fact = 1

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


fact *= i
res = res + (i/ fact)

return res
n=5
print("Sum: ", sumofSeries(n))

Output:
Sum: 2.70833
ADP MANUAL

D)In number theory, an abundant number or excessive number is a number for which the sum of its
proper divisors is greater than the number itself. Write a program to find out, if the given number is
abundant. (Input: 12, Sum of divisors of 12 = 1 + 2 + 3 + 4 + 6 = 16, sum of divisors 16 > original number
12)

# An Optimized Solution to check Abundant Number


# in PYTHON
import math

# Function to calculate sum of divisors


def getSum(n) :
sum = 0
# Note that this loop runs till square root
# of n
i=1
while i <= (math.sqrt(n)) :
if n%i == 0 :
# If divisors are equal,take only one
# of them
if n//i == i :
sum = sum + i
else : # Otherwise take both
sum = sum + i
sum = sum + (n // i )
i=i+1
# calculate sum of all proper divisors only
sum = sum - n
return sum
# Function to check Abundant Number
def checkAbundant(n) :
# Return true if sum of divisors is greater
# than n.
if (getSum(n) > n) :
return 1
else :
return 0
# Driver program to test above function */
if(checkAbundant(12) == 1) :
print ("YES")
else :
print ("NO")
if(checkAbundant(15) == 1) :
print ("YES")
else :
print ("NO")

Output:
YES
NO
ADP MANUAL

3: PROGRAMS ON LIST
a). Read a list of numbers and print the numbers divisible by x but not by y (Assume x = 4 and y = 5).
def result(N):
# iterate from 0 to N
for num in range(N):
# Short-circuit operator is used
if num % 4 == 0 and num % 5 != 0:
print(str(num) + " ", end = "")
else:
pass
# Driver code
if __name__ == "__main__":
# input goes here
N = 100
# Calling function
result(N)
output:- 4 8 12 16 24 28 32 36 44 48 52 56 64 68 72 76 84 88 92 96
ADP MANUAL

B). Read a list of numbers and print the sum of odd integers and even integers from the list.(Ex: [23, 10,
15, 14, 63], odd numbers sum = 101, even numbers sum = 24)
# Python program to count Even
# and Odd numbers in a List
NumList = []

Even_Sum = 0

Odd_Sum = 0

j=0

Number = int(input("Please enter the Total Number of List Elements: "))

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

value = int(input("Please enter the Value of %d Element : " %i))

NumList.append(value)

while(j < Number):

if(NumList[j] % 2 == 0):

Even_Sum = Even_Sum + NumList[j]

else:

Odd_Sum = Odd_Sum + NumList[j]

j = j+ 1

print("\nThe Sum of Even Numbers in this List = ", Even_Sum)

print("The Sum of Odd Numbers in this List = ", Odd_Sum)

Output:
Please enter the total number of list elements: 5
Please enter the value of 1 element:23
Please enter the value of 2 element:10
Please enter the value of 3 element:15
Please enter the value of 4 element:14
Please enter the value of 5 element:63
Sum of Even Numbers in this List=24
Sum of odd Numbers in this List =101
ADP MANUAL

c. Read a list of numbers and print numbers present in odd index position. (Ex: [10, 25, 30, 47, 56, 84, 96],
The numbers in odd index position: 25 47 84).
Program:
# Python3 implementation to
# arrange odd and even numbers
arr = list()
print(end="Enter the List Size: ")
arrTot = int(input())
print(end="Enter " +str(arrTot)+ " Numbers: ")
for i in range(arrTot):
arr.append(int(input()))
print("\nNumbers at Odd Position: ")
for i in range(arrTot):
if i%2!=0:
print(end=str(arr[i]) +" ")
print()
Output:- Enter the List Size: 7
Enter the 7 number10
25
30
47
56
84
Numbers at the odd position 25 47 84
ADP MANUAL

d). Read a list of numbers and remove the duplicate numbers from it. (Ex: Enter a list with duplicate
elements: 10 20 40 10 50 30 20 10 80, The unique list is: [10, 20, 30, 40, 50, 80]
Program:
my_list = [10,20,40,10,50,30,20,10,80]
print("List Before ", my_list)
temp_list = []
for i in my_list:
if i not in temp_list:
temp_list.append(i)
my_list = temp_list
print("List After removing duplicates ", my_list)

Output:
List Before [10,20,40,10,50,30,20,10,80]
List After removing duplicates [10,20,40,50,30,80]
ADP MANUAL

PROGRAMS ON TUPLE
a. Given a list of tuples. Write a program to find tuples which have all elements divisible by K from a
list of tuples. test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6, Output : [(6, 24, 12), (60, 12, 6)]
Program:
test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K=6
# all() used to filter elements
res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
# printing result
print("K Multiple elements tuples : " + str(res))
Output
The original list is: = [(6, 24, 12), (60, 12, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12), (60, 12, 6)]
ADP MANUAL

B) b. Given a list of tuples. Write a program to filter all uppercase characters tuples from given list of
tuples. (Input: test_list = [(“GFG”, “IS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)],
Output : [(„GFG‟, „IS‟, „BEST‟)]).
Program
test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("Gfg", "CS")]
# printing original list
print("The original list is : " + str(test_list))
res_list = []
for sub in test_list:
res = True
for ele in sub:
# checking for uppercase
if not ele.isupper():
res = False
break
if res:
res_list.append(sub)
# printing results
print("Filtered Tuples : " + str(res_list))
Output
The original list is : [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("Gfg", "CS")]
Filtered Tuples : [("GFG", "IS", "BEST")]
ADP MANUAL

c. Given a tuple and a list as input, write a program to count the occurrences of all items of the list in the
tuple. (Input : tuple = ('a', 'a', 'c', 'b', 'd'), list = ['a', 'b'], Output : 3)
Program:
# Python3 Program to count occurrence
# of all elements of list in a tuple
from collections import Counter
def countOccurrence(tup, lst):
count = 0
for item in tup:
if item in lst:
count+= 1
return count
# Driver Code
tup = ('a', 'a', 'c', 'b', 'd')
lst = ['a', 'b']
print(countOccurrence(tup, lst))
Output: 3
ADP MANUAL

PROGRAMS ON SET
a) Write a program to generate and print a dictionary that contains a number (between 1 and n) in the
form (x, x*x)

Program:
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Output:
Input a number 4
{1: 1, 2: 4, 3: 9, 4: 16}
ADP MANUAL

B ) Write a program to perform union, intersection and difference using Set A and Set B

Program:
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference
print("symmetric difference: ",A ^B)
Output:
Union : {0,1,2,3,4,5,6,8}
Intersection : {2,4}
Difference : {0, 8, 6}
symmetric difference : {0,1,3,5,6,8}
ADP MANUAL

C).Write a program to count number of vowels using sets in given string (Input : “Hello World”, Output:
No. of vowels : 3)

Program:
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count) # Driver code
str = "Hello World"
vowel_count(str)
Output:
No. of vowels : 3
ADP MANUAL

D).Write a program to form concatenated string by taking uncommon characters from two strings using
set concept (Input : S1 = "aacdb", S2 = "gafd", Output : "cbgf").

Program:
def concatenetedString(s1, s2):
res = "" # result
m = {}

# store all characters of s2 in map


for i in range(0, len(s2)):
m[s2[i]] = 1

# Find characters of s1 that are not


# present in s2 and append to result
for i in range(0, len(s1)):
if(not s1[i] in m):
res = res + s1[i]
else:
m[s1[i]] = 2

# Find characters of s2 that are not


# present in s1.
for i in range(0, len(s2)):
if(m[s2[i]] == 1):
res = res + s2[i]

return res

# Driver Code
if __name__ == "__main__":
s1 = " aacdb "
s2 = " gafd "
print(concatenetedString(s1, s2))

Output: cbgf
ADP MANUAL

PROGRAMS ON DICTONARY
a. Write a program to do the following operations:
i. Create a empty dictionary with dict() method
Program:
# Python3 code to demonstrate use of
# {} symbol to initialize dictionary
emptyDict = {}
# print dictionary
print(emptyDict)
# print length of dictionary
print("Length:", len(emptyDict))
# print type
print(type(emptyDict))

output :-
Length: 0
<type 'dict'>

ii. Add elements one at a time


Program:
d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
Output:
{'key': 'value'}
{'mynewkey': 'mynewvalue', 'key': 'value'}
ADP MANUAL

iii. Update existing key‟s value


Program:
a_dictionary = {"a": 1, "b": 2}
a_dictionary.update({"a": 0, "c": 3})
#Update with new keys and values
print(a_dictionary)
output:-
{'a': 0, 'c': 3, 'b': 2}
iv. Access an element using a key and also get() method
Program:
# initializing dictionary
test_dict = {'Gfg' : {'is' : 'best'}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using nested get()
# Safe access nested dictionary key
res = test_dict.get('Gfg', {}).get('is')
# printing result
print("The nested safely accessed value is : " + str(res))
Output:
The original dictionary is : = {'Gfg' : {'is' : 'best'}}
The nested safely accessed value is : best
v. Deleting a key value using del() method
Program:
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
print ("The dictionary before performing remove is : " + str(test_dict))
del test_dict['Mani']
print ("The dictionary after remove is : " + str(test_dict))
del test_dict['Manjeet']
output:-
The dictionary before performing remove is : {'Mani': 21, 'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}
The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}
ADP MANUAL

b. Write a program to create a dictionary and apply the following methods:


i. pop() method
Program:
test_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2}
print("The dictionary before deletion : " + str(test_dict))
pop_ele = test_dict.pop('Akash')
print("Value associated to poppped key is : " + str(pop_ele))
print("Dictionary after deletion is : " + str(test_dict))

output:-
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Value associated to poppped key is : 2
Dictionary after deletion is : {'Nikhil': 7, 'Akshat': 1}

ii. popitem() method


Program:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)

output:-
{'model': 'Mustang', 'year': 1964}
ii. clear() method
Program:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
output:-
{}
ADP MANUAL

c. Given a dictionary, write a program to find the sum of all items in the dictionary.
Program:
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
dict = {'a': 100, 'b':200, 'c':300}
print("Sum :", returnSum(dict))

output:-
('Sum :', 600)

d. Write a program to merge two dictionaries using update() method.


Program:
def Merge(dict1, dict2):
return(dict2.update(dict1))
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
print(Merge(dict1, dict2))
print(dict2)
output:-
None
{'a': 10, 'c': 4, 'b': 8, 'd': 6}
ADP MANUAL
7: STRINGS

A). Given a string, write a program to check if the string is symmetrical and palindrome or not. A string is said to be symmetrical if both the
halves of the string are the same and a string is said to be a palindrome string if one half of the string is the reverse of the other half or if a
string appears same when read forward or backward.

def palindrome(a):

mid = (len(a)-1)//2

start = 0

last = len(a)-1

flag = 0

while(start <= mid):

if (a[start]== a[last])

start += 1

last -= 1

else:

flag = 1

break

if flag == 0:

print("The entered string is palindrome")

else:print("The entered string is not palindrome")

def symmetry(a):

n = len(a)

flag = 0

if n%2:

mid = n//2 +1

else:

mid = n//2

start1 = 0

start2 = mid

while(start1 < mid and start2 < n):

if (a[start1]== a[start2]):

start1 = start1 + 1

start2 = start2 + 1

else:

flag = 1

break

if flag == 0:

print("The entered string is symmetrical")

else:

print("The entered string is not symmetrical")

string = 'amaama'

palindrome(string)
ADP MANUAL
symmetry(string)

output:- The entered string is palindrome

The entered string is symmetrical’

b.write a program to read a string and count the number of vowel letters and print all letters except ‘e’
and ‘s’.
Program:
def Check_Vow(string, vowels):
final = [each for each in string if each in vowels]
print(len(final))
print(final)

# Driver Code
string = "I love you devanshi"
vowels = "AaIiOoUu"
Check_Vow(string, vowels);
output:- 6 ['i', 'o', 'o', 'u', 'a',’i’]

c. Write a program to read a line of text and remove the initial word from given text. (Hint: Use split()
ADP MANUAL

method, Input : India is my country. Output : is my country)


def reverse_word(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start = start + 1
end -= 1
s = "i like this program very much"
# Convert string to list to use it as a char array
s = list(s)
start = 0
while True:
# We use a try catch block because for
# the last word the list.index() function
# returns a ValueError as it cannot find
# a space in the list
try:
# Find the next space
end = s.index(' ', start)
# Call reverse_word function
# to reverse each word
reverse_word(s, start, end - 1)
#Update start variable
start = end + 1
except ValueError:
# Reverse the last word
reverse_word(s, start, len(s) - 1)
break
# Reverse the entire list
s.reverse()
# Convert the list back to
# string using string.join() function
s = "".join(s)
print(s)
# Solution contributed by Prem Nagdeo
output:-
much very program this like i
d. Write a program to read a string and count how many times each letter appears. (Histogram).
ADP MANUAL

Program:
test_str = "Gandham"
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
# printing result
print ("Count of all characters in GeeksforGeeks is :\n "+ str(all_freq))
Output
Count of all characters in Gandham is :
{‘G’: 1, ‘a’:2 , ‘n’: 1, ‘d’: 1, ‘h’: 1, ‘m’:1}

8: USER DEFINED FUNCTIONS


ADP MANUAL

a. A generator is a function that produces a sequence of results instead of a single value. Write a
generator function for Fibonacci numbers up to n.

def fib(num):
a=0
b=1
for i in range(num):
yield a
a, b = b, a + b # Adds values together then swaps them
for x in fib(10):
print(x)
Output:
0
1
1
2
3
5
8
13
21
34

b. Write a function merge_dict(dict1, dict2) to merge two Python dictionaries.


Program:
def Merge(dict1, dict2):
return(dict2.update(dict1))

dict1 = {'a': 10, 'b': 8}


dict2 = {'d': 6, 'c': 4}
print(Merge(dict1, dict2))
print(dict2)

output:-
None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}

c. Write a fact() function to compute the factorial of a given positive number.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

output:-
Input a number to compute the factiorial : 4
24

d. Given a list of n elements, write a linear_search() function to search a given element x in a list.
ADP MANUAL

Program:
def search(arr, n, x):

for i in range(0, n):


if (arr[i] == x):
return i
return -1
arr = [2, 3, 4, 10, 40]
x = 10
n = len(arr)
result = search(arr, n, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result)

output:-
Element is present at index 3

BUILT IN FUNCTIONS
ADP MANUAL

a).Write a program to demonstrate the working of built-in statistical functions mean(), mode(),
median() by importing statistics library.
Program:
import statistics
li = [1, 3, 3, 2, 2, 1]
# using mean() to calculate average of list elements
print ("The average of list values is : ",end="")
print (statistics.mean(li))
# using mode() to print maximum occurring of list elements
print ("The maximum occurring element is : ",end="")
print (statistics.mode(li))
# using median() to print decimal occurring of list elements
print ("The maximum occurring element is : ",end="")
print (statistics.median(li))
Output
The average of list values is : 2
The maximum occurring element is : 1
The maximum occurring element is : 2.0

b.Write a program to demonstrate the working of built-in trignometric functions sin(), cos(), tan(),
hypot(), degrees(), radians() by importing math module.
Program:
import math
print(math.sin(math.pi/3)) #pi/3 radians is converted to 60 degrees
print(math.tan(math.pi/3))
print(math.cos(math.pi/6))
print(math.degrees((math.pi/2)))
print(math.radians(60))
print(math.hypot(3))
OUTPUT:-
0.8660254037844386
1.7320508075688767
0.8660254037844387
90.0
1.0471975511965976
3.0
ADP MANUAL

C) Write a program to demonstrate the working of built-in Logarithmic and Power functions exp(),
log(), log2(), log10(), pow() by importing math module
Program:
# Python code to demonstrate the working of
# log(a,Base)
import math
# Printing the log base e of 14
print ("Natural logarithm of 14 is : ", end="")
print (math.log(14))
# Printing the log base 5 of 14
print ("Logarithm base 5 of 14 is : ", end="")
print (math.log(14,5))
output:- Natural logarithm of 14 is : 0.0
Logarithm base 5 of 14 is : 0.6931471805599453
the exponatial of the 12 is : 162754.79141900392

D.Write a program to demonstrate the working of built-in numeric functions ceil(), floor(), fabs(),
ADP MANUAL

factorial(), gcd() by importing math module.

import math
a = 2.3
# returning the ceil of 2.3
print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))
# returning the floor of 2.3
print ("The floor of 2.3 is : ", end="")
print (math.floor(a))
a = -10
b= 5
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))
# returning the factorial of 5
print ("The factorial of 5 is : ", end="")
print (math.factorial(b))
a = -10
b = 5.5
c = 15
d=5
# returning the copysigned value.
print ("The copysigned value of -10 and 5.5 is : ", end="")
print (math.copysign(5.5, -10))
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print (math.gcd(5,15))
OUTPUT:-
The ceil of 2.3 is : 3
The floor of 2.3 is : 2
The absolute value of -10 is : 10.0
The factorial of 5 is : 120
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5
ADP MANUAL

10. CLASS AND OBJECTS


a. Write a program to create a BankAccount class. Your class should support the following methods for i)
Deposit ii) Withdraw iii) GetBalanace iv) PinChange
Program:
import time
print("****************************************")
pin=int(input("enter your pin code:"))
if pin==3823:
print("welcome to Dev bank")
print("1.withdraw")
print("2.transfer money")
print("3.balance enquiry.")
print("4.pin change")
print("****************************************")
choice=int(input("enter your choice here:"))
if choice==1:
print("1.savings")
print("2.current")
pr=int(input("enter your choice:"))
if pr==1:
cash=int(input("enter the cash below:"))
print("wait!")
time.sleep(2.0)
bal=40000-cash
print("balance left :",bal)
print("****************************************")
elif pr==2:
cash2=int(input("enter the cash below"))
bal=40000-cash
print("balance left :",bal)
print("****************************************")
elif choice==2:
name=input("enter reciever name :")
acc=int(input("enter acc number :"))
if acc==123456789 and name=="Dev":
time.sleep(2.0)
print("transation completed")
ADP MANUAL

else:
print("timed out!")

elif choice==3:
print("balance left in your account")
time.sleep(2.0)
print("40000 /-")

elif choice==4:
old=int(input("enter old pin number :"))
new=int(input("enter new pin number :"))
time.sleep(2.0)
print("pin number changed")
print("thank you for your service")
Output
****************************************
enter your pin code:3823
welcome to Dev bank
1.withdraw
2.transfer money
3.balance enquiry.
4.pin change
****************************************
enter your choice here:1
1.savings
2.current
enter your choice:1
enter the cash below:10000
wait!
balance left : 30000
****************************************
****************************************
enter your choice here:3
balance left in your account
40000 /-
****************************************
enter your pin code:3823
ADP MANUAL

welcome to Dev bank


1.withdraw
2.transfer money
3.balance enquiry.
4.pin change
****************************************
enter your choice here:4
enter old pin number :3823
enter new pin number :3228
pin number changed
thank you for your service
ADP MANUAL

C) Create a SavingsAccount class that behaves just like a BankAccount, but also has an interest rate and
a method that increases the balance by the appropriate amount of interest (Hint:use Inheritance).
Program:
from datetime import datetime
class Account:
total_accounts = 0
interest_rate = 0.04
def __init__(self, act_no, act_balance, type):
self.act_no = act_no
self.act_balance = act_balance
self.type = type
self.created_date= datetime.now()
Account.total_accounts += 1
def returns(self, year):
return f'Your balance is worth {self.act_balance * 1.04} in {year} year(s)'
class MultiCurrencyAccount(Account):
interest_rate = 0.01
def __init__(self, act_no, act_balance, type, currencies):
self.currencies=currencies
super().__init__(act_no,act_balance,type)
myaccount=Account(5555555005,100,"savings")
print(myaccount.returns(1))
print(myaccount.returns(2))
Output
Your balance is worth 104.0 in 1 year(s)
Your balance is worth 104.0 in 2 year(s)
ADP MANUAL

C). Write a program to create an employee class and store the employee name, id, age, and salary using
the constructor. Display the employee details by invoking employee_info() method and also using
dictionary (__dict__).
Program:
class Employee:
__id=0
__name=""
__gender=""
__city=""
__salary=0

# function to set data


def setData(self,id,name,gender,city,salary):
self.__id=id
self.__name = name
self.__gender = gender
self.__city = city
self.__salary = salary
# function to get/print data
def showData(self):
print("Id\t\t:",self.__id)
print("Name\t:", self.__name)
print("Gender\t:", self.__gender)
print("City\t:", self.__city)
print("Salary\t:", self.__salary)
# main function definition
def main():
emp=Employee()
emp.setData(1,'Devanshi','female','Bangalore',55000)
emp.showData()
if __name__=="__main__":
main()
Output:
Id : 1
Name : Devanshi
Gender: female
City : Bangalore
Salary : 55000
ADP MANUAL

d. Access modifiers in Python are used to modify the default scope of variables. Write a program to
demonstrate the 3 types of access modifiers: public, private and protected.
Program:
class Super:
# public data member
var1 = None
# protected data member
_var2 = None

# private data member


__var3 = None
# constructor
def __init__(self, var1, var2, var3):
self.var1 = var1
self._var2 = var2
self.__var3 = var3

# public member function


def displayPublicMembers(self):
# accessing public data members
print("Public Data Member: ", self.var1)
# protected member function
def _displayProtectedMembers(self):
# accessing protected data members
print("Protected Data Member: ", self._var2)
# private member function
def __displayPrivateMembers(self):
# accessing private data members
print("Private Data Member: ", self.__var3)
# public member function
def accessPrivateMembers(self):
# accessing private member function
self.__displayPrivateMembers()
# derived class
class Sub(Super):
# constructor
def __init__(self, var1, var2, var3):
Super.__init__(self, var1, var2, var3)
ADP MANUAL

# public member function


def accessProtectedMembers(self):
# accessing protected member functions of super class
self._displayProtectedMembers()

# creating objects of the derived class


obj = Sub("Devanshi", 4, "Gandham !")
# calling public member functions of the class
obj.displayPublicMembers()
obj.accessProtectedMembers()
obj.accessPrivateMembers()
# Object can access protected member
print("Object is accessing protected member:", obj._var2)
Output
Public Data Member: Devanshi
Protected Data Member: 4
Private Data Member: Gandham !
Object is accessing protected member: 4

11. FILE HANDLING


ADP MANUAL

a. . Write a program to read a filename from the user, open the file (say firstFile.txt) and then perform
the following operations:
i. Count the sentences in the file.

Program:
# Opening a file
file = open("mytext.txt","r")
Counter = 0
# Reading from file
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
print("This is the number of lines in the file")
print(Counter)
Output
This is the number of lines in the file
3
ii. Count the words in the file.
Program:
def display_words():
file = open("mytext.txt","r")
data = file.read()
words = data.split()
print("number of words in file:",len(words))
file.close()
display_words()
Output
number of words in file: 14

iii. Count the characters in the file.


ADP MANUAL

Program:
file = open("mytext.txt", "r")
#read the content of file
data = file.read()
#get the length of the data
number_of_characters = len(data)
print('Number of characters in text file :', number_of_characters)
Output
Number of characters in text file : 87

b. . Create a new file (Hello.txt) and copy the text to other file called target.txt. The target.txt file
should store only lower case alphabets and display the number of lines copied

Program:
with open('mytext.txt','r') as firstfile, open('second.txt','a') as secondfile:

# read content from first file


for line in firstfile:

# append content to second file


secondfile.write(line)
Output

If you run this automatically create the 2nd new file name with second,txt
In that file automatically generate the information from mytext.txt

C). c. Write a Python program to store N student‟s records containing name, roll number and branch. Print
the given branch student‟s details only.
ADP MANUAL

Program:

class Student:
marks = []
def getData(self, rn, name, m1, m2, m3):
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)

def displayData(self):
print ("Roll Number is: ", Student.rn)
print ("Name is: ", Student.name)
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
print ("Average Marks are: ", self.average())

def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])

def average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)

r = int (input("Enter the roll number: "))


name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))

s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()

Output
Enter the roll number: 528
Enter the name: kiran
Enter the marks in the first subject: 59
Enter the marks in the second subject: 69
Enter the marks in the third subject: 78
Roll Number is: 528
Name is: kiran
Marks are: [59, 69, 78]
Total Marks are: 206
Average Marks are: 68.66666666666667

DBMS Commands
1. Implement Data Definition Language(DDL) Statements: (Create table, Alter table, Drop table) 2.
1.Implement Data Manipulation Language(DML) Statements
ADP MANUAL

DDL

o CREATE
o ALTER
o DROP
o TRUNCATE

CREATE:

CREATE TABLE Student(Sid int, Sname VARCHAR2(20), Address VARCHAR2(100));

ALTER:
ALTER TABLE Student ADD Number int;
ALTER TABLE Student Drop column Number;
ALTER TABLE Student Alter Number BIgint;

DROP

Drop table Student

Truncate
Truncate table Student

DML

o INSERT
o UPDATE
o DELETE
o SELECT

INSERT

Insert into Student(Sid,Sname,Address,Number) values(101,”dev”,”nandyal”,34534);

UPDATE

Update table set Number=858585 where Sid=101;

o DELETE

Delete from Student where Sid=102;

SELECT

Select * from Student;

Select Sid from Student where Sname=”dev”;

You might also like