1. Python Program to Check Armstrong Number.
Make the function
for it. Armstrong number: A number is called Armstrong number if
it is equal to the sum of the cubes of its own digits. For example: 153
is an Armstrong number since 153 = 1*1*1 + 5*5*5 + 3*3*3.
Program-
Number = 153
Temp=number
Add sum=0
While temp! =0
K=temp%10
Add_sum+=k*k*k
Temp=temp//10
If add_sum==number:
Print (“given number is a three digit Armstrong number”)
Else:
Print (“given number is not an Armstrong number”)
Output:
Given number is a three – digit Armstrong number.
-----------------------------------------------------------------------------------------------------------------
2. Define multiple decorator functions to find out square root in second
decorator and then factorial of square root in first decorator function
of a given number.
Program:
def factorial(func):
def inner(num):
fact = 1
for i in range(1, int(func(num))+1):
fact *= i
return fact
return inner
def square_root(func):
def inner(num):
sqr = num**0.5
return sqr
return inner
@factorial
@square_root
def sqrt_then_factorial(num):
return num
print(sqrt_then_factorial(25))
--------------------------------------------------------------------------------------------------------------------------------------
3. Write a python program to calculate average of given numbers using
Lambda function.
Program:
From functools import reduce
inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88]
lst_len= len(inp_lst)
lst_avg = reduce(lambda x, y: x + y, inp_lst) /lst_len
print ("Average value of the list:\n")
print (lst_avg)
print ("Average value of the list with precision upto 3 decimal value:\n")
print (round(lst_avg,3))
---------------------------------------------------------------------------------------------------------------------------
4. Python program to calculate discount based on selling price using
class and Object. Take product name, rate and quantity as a input.
The discount will be calculated as, If the order amount is greater
than 100000 is 20%. If the order amount is greater than 50000 and
smaller than 100000 is 10%. If the order amount is smaller than
50000 is 5%. In this program, we will use the if-else ladder to
calculate different discounts
Program:
class product:
def__init__(self,name,rate,amount):
[Link]=name
[Link]=rate
[Link]=amount
def get_price(self,quantity)
Discount=0
if (quantity>=10000):
Discount=20%
Elif (quantity>=5000 and quantity<=99999):
Discount =10%
Elif:
Discount = 5%
Def make_purchase (self,size):
[Link]-=size
Name, amount, rate =”shoe”, 200, 33
Shoes= product (name, amount, price)
q1=4
shoes.make_purchase(q1)
print (“cost for {q1} {[Link]} = {shoes.get_price (q1)})
--------------------------------------------------------------------------------------------------------------------------------------
5. a) Write a python program to validate website URL using Regular
Expression.
Program:
import re
def isValidURL(str):
regex = ("((http|https)://)(www.)?" +
"[a-zA-Z0-9@:%._\\+~#?&//=]" +
"{2,256}\\.[a-z]" +
"{2,6}\\b([-a-zA-Z0-9@:%" +
"._\\+~#?&//=]*)")
p = [Link](regex)
if (str == None):
return False
if([Link](p, str)):
return True
else:
return False
url = "[Link]
if(isValidURL(url) == True):
print("Yes")
else:
print("No")
--------------------------------------------------------------------------------------------------------------------------------------
b) Write a Python program to count the number of lines in a file.
Program:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(file_len("my_file.txt"))
--------------------------------------------------------------------------------------------------------------------------------------
6. a) Write a python program to perform Exception handling (Divide
by zero Exception)
Program:
try:
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c=a/b
print("The division of the two numbers is: ", c)
except ZeroDivisionError:
print("Division by zero is not allowed")
except ValueError:
print("Enter valid numbers")
except Exception:
print("Something went wrong")
----------------------------------------------------------------------------------------------------------------
b) Write a program for IndexError Exception in Python with
Example.
Program:
try:
list = [1, 2, 3, 4, 5]
# print the element at index 5
print(list[5])
except IndexError:
print("IndexError Exception")
except Exception:
print("Exception")
else:
print("No exception")
----------------------------------------------------------------------------------------------------------------
7. Write a Python program to count total number of uppercase and
lowercase characters in file.
Program:
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if([Link]()):
count1=count1+1
elif([Link]()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
----------------------------------------------------------------------------------------------------------------
8. a) Write a Python Program to illustrate parameterized threads.
Program:
import threading
import time
def ProcessOne(*param):
while(True):
print(param[0],threading.current_thread().getName(),"is Running",param[1])
[Link](param[2])
def ProcessTwo(*param):
while(True):
print(param[0],threading.current_thread().getName(),"is Running",param[1])
[Link](param[2])
T1=[Link](target=ProcessOne,name="Swift",args=('Maruti',200,1))
T2=[Link](target=ProcessTwo,name='I20',args=('Hyundai',220,5))
[Link]()
[Link]()
---------------------------------------------------------------------------------------------------------------------------
b) Write a Python program to create and delete threads using sleep
method.
Program:
import threading
import time
class ServiceProvider([Link]):
def run(self):
while True:
print("Service Provider....")
[Link](1)
print("IN MAIN PROGRAM")
S=ServiceProvider()
[Link](True)
[Link]()
[Link](5)
print("END OF MAIN PROGRAM")
----------------------------------------------------------------------------------------------------------------
9. Write the python program to insert 10 records in Doctor collection
and and write a query,
1. To return documents where salary is <= 60000
2. To return documents where salary is > 60000
3. To return documents with specific speciality
Program-
doctors_list = [
{
"name": "Dr. John",
"speciality": "Cardiology",
"salary": 60000
},
{
"name": "Dr. Paul",
"speciality": "Orthopedics",
"salary": 50000
},
{
"name": "Dr. Smith",
"speciality": "Cardiology",
"salary": 70000
},
{
"name": "Dr. Peter",
"speciality": "Orthopedics",
"salary": 80000
},
{
"name": "Dr. James",
"speciality": "Cardiology",
"salary": 90000
},
{
"name": "Dr. John",
"speciality": "Orthopedics",
"salary": 100000
},
{
"name": "Dr. Paul",
"speciality": "Cardiology",
"salary": 110000
},
{
"name": "Dr. Smith",
"speciality": "Orthopedics",
"salary": 120000
},
{
"name": "Dr. Peter",
"speciality": "Cardiology",
"salary": 130000
}
]
def get_db():
from pymongo import MongoClient
DB_URI = <db_address>
client = MongoClient(DB_URI)
db = client.<your db>
return db
db = get_db()
db.drop_collection("doctors")
col_doctors = [Link]
col_doctors.insert_many(doctors_list)
def print_doctors(results):
print("-" * 50)
print(f"{'Name':<20} {'Speciality':<20} {'Salary':<20}")
print("-" * 50)
for result in results:
print(
f"{result['name']:<20} {result['speciality']:<20} {result['salary']:<20}")
print()
def doc_sal_lt_60k():
results = col_doctors.find({"salary": {"$lte": 60000}})
print(f"{'Salary less than 60000':^50}")
print_doctors(results)
def doc_sal_gt_60k():
results = col_doctors.find({"salary": {"$gt": 60000}})
print(f"{'Salary greater than 60000':^50}")
print_doctors(results)
def get_docs(speciality):
results = col_doctors.find({"speciality": speciality})
print(f"{'Doctors with speciality in ' + speciality:^50}")
print_doctors(results)
doc_sal_lt_60k()
doc_sal_gt_60k()
get_docs("Cardiology")
----------------------------------------------------------------------------------------------------------------
10.a) Write a python program to create numpy array and use the
functions as Zeros, ones, linspace, random and sum of array.
Program-
import numpy as np
num_sq = [Link]([[i, i**2] for i in range(5)])
print(num_sq)
num_zero = [Link]((2,2))
print(num_zero)
num_one = [Link]((2,2))
print(num_one)
linsp = [Link](2, 3, 3)
print(linsp)
rand_arr = [Link](2,2)
print(rand_arr)
sum_num_sq = [Link](num_sq)
print(sum_num_sq)
----------------------------------------------------------------------------------------------------------------
b) Write a python code to create pandas data frame of students details of 10
students like [Link], Name, DOB, Address, Email_ID, Contact_No,
Blood_Group, Course etc. and import it into [Link] file
program-
import pandas as pd
students_list = [
{
"roll_no": 1,
"name": "Jolie Lygo",
"dob": "11/23/1998",
"email": "jlygo0@[Link]", "address": "622 Derek Drive"
},
{
"roll_no": 2,
"name": "Kellen Killiner",
"dob": "2/11/1999",
"email": "kkilliner1@[Link]", "address": "0 Scofield Point"
},
{
"roll_no": 3,
"name": "Rickie Texton",
"dob": "7/21/1997",
"email": "rtexton2@[Link]", "address": "3356 Cordelia Terrace"
},
{
"roll_no": 4,
"name": "Kelli Gofton",
"dob": "5/7/1998",
"email": "kgofton3@[Link]", "address": "4376 Beilfuss Road"
},
{
"roll_no": 5,
"name": "Jacklyn Ellison",
"dob": "9/22/1998",
"email": "jellison4@[Link]", "address": "465 Clyde Gallagher Alley"
},
{
"roll_no": 6,
"name": "Philippe Chitson",
"dob": "9/4/1999",
"email": "pchitson5@[Link]", "address": "71 Burning Wood Avenue"
},
{
"roll_no": 7,
"name": "Bartholomeus Huchot",
"dob": "5/16/1996",
"email": "bhuchot6@[Link]", "address": "9172 Namekagon Parkway"
},
{
"roll_no": 8,
"name": "Vin Manby",
"dob": "6/10/1997",
"email": "vmanby7@[Link]", "address": "21 Ilene Street"
},
{
"roll_no": 9,
"name": "Hewet Hamm",
"dob": "3/19/1997",
"email": "hhamm8@[Link]", "address": "0 Larry Junction"
},
{
"roll_no": 10,
"name": "Clyve Seakin",
"dob": "4/15/1995",
"email": "cseakin9@[Link]", "address": "3 Stang Drive"
}
]
df = [Link].from_dict(students_list)
df.to_csv("[Link]", index=False)
----------------------------------------------------------------------------------------------------------------
c)Plot graph for equation
1. y=2x^2+2x+10
2. y=2x+5
Program-
import [Link] as plt
import numpy as np
x = [Link](-2, 2, 100)
y = (2*(x**2)) + (2*x) + 10
a = [Link](-2, 2, 100)
b = (2*x)+5
fig = [Link](figsize=(10, 5))
[Link](x, y)
[Link](a, b)
[Link](True)
[Link]('x')
[Link]('y')
[Link]('Plot of y = 2x² + 2x + 10')
[Link] (['y = 2x² + 2x + 10', 'y = 2x + 5'])
[Link]()
----------------------------------------------------------------------------------------------------------------