8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your basics in designing.
1. 1
1) Read a path from user and display all directories and files on that path
along with their properties. (Python)
# import OS module
import os
# Get the list of all files and directories
path = "C:UsersIMRDDesktopABC"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# prints all files
print(dir_list)
2) Write a program to demonstrate class, object, Inheritance. (Python)
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
2. 2
3) Write a program to demonstrate Module and Package. (Python)
File 1) mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
File 2) File2.py
import mymodule #mymodule is the first file name
a = mymodule.person1["age"]
print(a)
Note: Run File2.py (save File 1 as a name mymodule.py and this name use as
a package in File 2)
4) Write a function to print prime number in the given range n1 to n2(Python)
lower=1
upper=10
print("Prime no.between",lower,"änd",upper,"are:")
for num in range(lower,upper+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
3. 3
5) Write a program to find sum of array.(Python)
def _sum(arr):
sum = 0
for i in arr:
sum = sum + i
return(sum)
# main function
if __name__ == "__main__":
# input values to list
arr = [12, 3, 4, 15]
n = len(arr)
ans = _sum(arr)
print('Sum of the array is ', ans)
Output: Sum of the array is 34
6) Demonstrate exception handling with minimum 3 types of
exception.(python)
i) Write.py
file=open("111.txt","w")
file.write("hey this is my file")
file.close()
ii) Read.py
file=open("111.txt","r")
someText=file.read()
print(someText)
file.close()
4. 4
iii) Append.py
file =open("111.txt" ,"a")
file.write("n new line ")
file.close()
7) Write and demonstrate program to read an integer and functions to check
given number is Armstrong or not. (Python).
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")
8) Write the program to read and multiply two matrices of given size. (Python)
# take a 2x2 matrix
A = [[2,2],
[1,1]]
# take a 2x2 matrix
B = [[7,1],
[11,2]]
5. 5
result = [[0, 0],
[0, 0,]]
# iterating by row of A
for i in range(len(A)):
# iterating by column by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
9) Write the program to demonstrate lambda and filter(Python)
d=lambda p:p*5
t=lambda p:p*2
x=7
x=d(x)
x=t(x)
x=d(x)
print(x)
nums=[6,16,26,36,46,56]
result=list(map(lambda x:x*2+2-4,nums))
print (result)
t=[1,2,3,4,5,6,7,8,9]
result=filter (lambda v:v%2!=0,t)
print (list(result))
6. 6
10) Create a dictionary by adding the key value pair from user. Check for
duplicate before adding. Display the value of key given by user. (Python)
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values())
11) Demonstrate List and Dictionary with its important function (minimum
4). (Python)
#List
a = ["abc", "pqr", "www"]
print(a)
print(a[1])
#define dictionary's
d={6:"six"}
d[5]="five"
d[10]="ten"
print("dictionary",d)
del d[10]
print("dictionary",d)
12) Write a program to read a path string from user and list all directories
and filename separately. (Python).
from os import walk
# folder path
7. 7
dir_path = r'Desktop'
# list to store files name
res = []
for (dir_path, dir_names, file_names) in walk(dir_path):
res.extend(file_names)
print(res)
13) Program to demonstrate function from path module. (Python)
# Python program to explain os.path.normpath() method
# importing os.path module
import os.path
# Path
path = 'Desktop'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
14) Program to demonstrate function from path module. (Python)
i) Join ii)Split
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(' ')
8. 8
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = '-'.join(list_string)
return string
# Driver Function
if __name__ == '__main__':
string = 'hey this is my file'
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string)
iii) normpath() Method
import os.path
path = r'C:/Users'
norm_path = os.path.normpath(path)
print(norm_path)
path = r'C:Users.Documents'
norm_path = os.path.normpath(path)
print(norm_path)
9. 9
path = r'C:Usersadmintemp..Documents'
norm_path = os.path.normpath(path)
print(norm_path)
Output: C:Users
C:UsersDocuments
C:UsersadminDocuments
iv) exit() Method
# Python program to demonstrate
# exit()
for i in range(10):
if i == 5:
print(exit)
exit()
print(i)
Output:
0
1
2
3
4
10. 10
15) Python Program for GUI Architecture-
i)Python Tkinter Widgets – Button
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg=messagebox.showinfo( "Hello Python", "Hello World")
B = Button(top, text ="Hello", command = helloCallBack)
B.place(x=50,y=50)
top.mainloop()
ii) Python Tkinter Widgets - Checkbutton:
>>> from tkinter import *
>>> top=Tk()
>>> CheckVar1=IntVar()
>>> CheckVar2=IntVar()
>>> C1=Checkbutton
>>>C1=Checkbutton(top,text="Pizza",variable=CheckVar1,onvalue=1,offvalue=0,h
eight=5,width=20)
>>>C2=Checkbutton(top,text="Fries",variable=CheckVar2,onvalue=1,offvalue=0,h
eight=5,width=20)
>>> C1.pack()
15. 15
>>> top.mainloop()
16)Write a function to replace smiley characters in a given sentence with Emoji
/ word sentiment using Dictionary. (Python)
# grinning face
print("U0001f600")
# grinning squinting face
print("U0001F606")
# rolling on the floor laughing
print("U0001F923")
#Crying face
print("N{crying face}")
# grinning face
print("N{grinning face}")
# slightly smiling face
print("N{slightly smiling face}")
# winking face
print("N{winking face}")
17) Create a sample log file and demonstrate Rotating of files
import logging
import time
from logging.handlers import RotatingFileHandler
16. 16
---------------------------------------------------------------------
def create_rotating_log(path):
"""
Creates a rotating log
"""
logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.INFO)
# add a rotating handler
handler = RotatingFileHandler(path, maxBytes=20,
backupCount=5)
logger.addHandler(handler)
for i in range(10):
logger.info("This is test log line %s" % i)
time.sleep(1.5)
----------------------------------------------------------------------
if __name__ == "__main__":
log_file = "test.log"
create_rotating_log(log_file)
NOTE-[Before executing this program make sure firstly you create folder and save
this program in a folder because log files is also create at same location.]