0% found this document useful (0 votes)
36 views

Pythonjornal

The document contains 25 Python programs covering topics like checking if a number is even/odd/prime, finding if a year is leap year, calculating factorials, finding multiples of a number, using classes and objects, regular expressions, and more. Each program has the code, input, and output sections.

Uploaded by

rohitadhari14802
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Pythonjornal

The document contains 25 Python programs covering topics like checking if a number is even/odd/prime, finding if a year is leap year, calculating factorials, finding multiples of a number, using classes and objects, regular expressions, and more. Each program has the code, input, and output sections.

Uploaded by

rohitadhari14802
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

1

1 Write a program to find whether a number is Even or Odd and Prime


Program:
x = int(input("Enter a number to find whether odd or even and to check whether
it is prime or not: "))

if x > 1:
for i in range(2, (x//2)+1):

if (x % i) == 0:
print(x, "is not a prime number")
break
else:
print(x, "is a prime number")
else:
print(x, "is not a prime number")

if x % 2 ==0:
print("Number is Even")
else:
print("Number is Odd")

Output:

2 Write a program to find whether a number is Armstrong or not.


Program:
y = x = int(input("Enter a number to check whether it is amstrong or not: "))
l = []

while x!=0:
l.append(x%10)
x//=10

s = sum(x**len(l) for x in l)
print(f"{y} is Amstrong" if s == y else f"{y} is not Amstrong")
2

Output:

3 Write a program to find out whether a year is Leap Year or not


Program:
x = int(input("Enter a year: "))

print(f"{x} is a leap year." if (x % 4 == 0 and x % 100 != 0) or (x % 400 ==


0) else f"{x} is not a leap year." )

Output:

4 Write a program to accept a number from the user and find the factorial of the
number.
Program:
x = int(input("Enter a number to find factorial: "))

if x == 0:
print("Factorial is 1")
elif x<0:
print("Enter a valid number")

for i in range(1,x):
x*=i

print(f"Factorial is {x}")
3

Output:

5 Write a program to find multiples of the given number.


Program:
x = int(input("Enter a number to find multiples of it: "))

print(f"Multiples of {x} upto 10 are: ",end="")

for i in range(1, 11):


print(x*i,end = " ")
Output:

6 Write a program to demonstrate the use of default parameters in methods.


Program:
def add(a, b=30):
print(f"addition of {a} and {b} is ",a+b)

add(20)
Output:
4

7 Write a python program to calculate the total number of upper case and lower
case characters.
Program:
x = input("Enter a string with a mix of uppercase and lowercase characters: ")
l,u=0,0

for i in x:
if i.isupper():
u+=1
elif i.islower():
l+=1

print(f"Number of uppercase letters are {u} and lowercase is {l}")


Output:

8 Write a python program to calculate the average of a given number using the
lambda function.
Program:
x = list(map(int, input("enter the numbers to find average: ").split()))

avg = lambda x: sum(x)/len(x)

print("Average is ",avg(x))
Output:
5

9 Write a program to define multiple decorator functions to find out square root
in the second decorator and then factorial of square root in the first decorator
function of a given number
Program:
def sqrt(x):
x **=0.5
def fact(y):
y=int(y)
for i in range(1,y):
y*=i
return y
return fact(x),x
a = int(input("Enter a positive natural number "))

x,y=sqrt(a)
print("Square root of {} is {} and its factorial is {}".format(a,y,x))
Output:

10 Write a program to define a simple class


Program:
class student:
name = ""
age = 0
div=""
std=""

s1 = student()

s1.name = "Rohit Adhari"


s1.age = 22
s1.div = "A"
s1.std = "XII"

print(f"Name: {s1.name} Age: {s1.age} Division: {s1.div} Standard: {s1.std}")


6

Output:

11 Write a program to illustrate the creation of multiple objects for a class.


Program:
class student:
def __init__(self,n,a,d,s) -> None:
self.name = n
self.age = a
self.div = d
self.std = s

def display(self):
print(f"Name: {self.name} Age: {self.age} Division: {self.div}
Standard: {self.std}")

s1 = student("Rohit", 22, "A", "XVI")


s2 = student("Aditya", 23, "B", "XVII")
s3 = student("Omkar", 24, "C", "XVI")

s1.display()
s2.display()
s3.display()
Output:
7

12 Write a program to demonstrate the use of constructor in a class.


Program:
class add:
def __init__(self,a,b) -> None:
self.a = a
self.b = b

def addition(self):
return self.a+self.b

n1= add(30,20)
print("addition of 10 and 20 is ",n1.addition())
Output:

13 Write a program to demonstrate the use of destructors in a class.


Program:
class demo:
def __init__(self):
print("Constructr called")

def __del__(self):
print("Destructor called")

d= demo()
Output:
8

14 Write a program to demonstrate dynamic attribute of a class


Program:
class h:
pass

x = h()
y = h()

x.a = "hi "


y.a = "hello"

print(x.a, y.a)
Output:

15 Write a program to call class methods using objects.


Program:
class demo:
def display(self):
print("Class method called")

demo.display = classmethod(demo.display)
demo.display()
Output:

16 Write a program to demonstrate the use of super function.


Program:
class A:
def __init__(self) -> None:
print("A's contructor was called")
9

class B(A):
def __init__(self) -> None:
super().__init__()
print("B's contructor was called")

b = B()

Output:

17 Write a program to calculate the arc length of an angle by assigning values to


the radius and angle data attributes of the class ArcLength
Program:
class ArcLength:
radius = 0
angle = 0

def cal(self):
print(f"Arclength of the given arc is {self.radius * self.angle}
units")

arc1 = ArcLength()
arc1.radius = 20
arc1.angle = 30
arc1.cal()
Output:
10

18 Write a python program to calculate gross pay(hourly paid employee) using


class and object The input as number of hour work and extra hours, payments
mode to the employee are basedOn the number of hours she has worked. The
working hour is 8 hours(per day) and the amount1500\- is paid. If work is less
than 8 hours, payment is75\- per hour.If work is more than 8 hours pay ₹75 per
Hour
Program:
class employee:
def __init__(self) -> None:
self.gross_pay = 0
self.hours = 0

def hours_worked(self,hours):
self.hours= hours
if hours >8:
self.gross_pay = 1500 + hours*75
elif hours == 8:
self.gross_pay = 1500
else:
self.gross_pay = hours*75

def gross_py(self):
print(f"You worked for {self.hours} today. Your gross pay is
{self.gross_pay}")

e1 = employee()
e1.hours_worked(10)
e1.gross_py()
e1.hours_worked(8)
e1.gross_py()
e1.hours_worked(2)
e1.gross_py()
Output:
11

19 Write a program to calc discount based on SP using class and object, take
product name, rate and quantity as input. the discount will be calculated as if
(order50000): discount=5%
Program:
class SP:
def __init__(self) -> None:
self.name, self.rate, self.quantity = list(input("Enter name, rate
and quantity ").split())

def amount(self):
order = int(self.rate)*int(self.quantity)

if order <10000: order *=80/100


elif order <=50000: order *= 90/100
elif order >50000: order *= 95/100
print("Order for {} amounts to {}".format(self.name,order))

o1 = SP()
o1.amount()
Output:

20 Write Python Program to Simulate a Bank Account for deposit, withdrawal


and balance Operations.
Program:
class Bank:
def __init__(self,bal) -> None:
self.balance = bal

def withdraw(self, amt):


self.balance-=amt
print("Amount withdrawn ",amt, " New Balance: ", self.balance)

def deposit(self, amt):


self.balance+=amt
print("Amount deposit ",amt, " New Balance: ", self.balance)
12

def display(self):
print("Current Balance",self.balance)

bank = Bank(500)

bank.deposit(400)
bank.withdraw(100)

bank.display()
Output:

21 Write a program to demonstrate use of delegates.


Program:
class college:
def get_name(self):
return "DYPIMR"
def get_add(self):
return "pimpri"

class student:
def __init__(self) -> None:
self.col = college()

def return_name(self):
return f"name of college is {self.col.get_name()} and address of
college is {self.col.get_add()}"

s1 = student()
print(s1.return_name())
13

Output:

22 Write a program using regular expressions to find all the digits in a string.
Program:
import re

s = input("Enter a string with only numbers ")


print("Only numbers" if re.findall(r"^[0-9]+$",s) else "Not all are numbers")
Output:

23 Write a program using regular expression to remove all whitespaces from a


string.
Program:

import re

s = input("Enter a string with whitespaces ")

s = re.sub(r"\s+","",s)
print(s)
14

Output:

24 Write a program to validate phone number using regular expressions.


Program:
import re
s = input("Enter your phone number ")

flag = re.compile("^[976]{1}[0-9]{9}")

if flag.match(s):
print("Valid mobile number")
else:
print("not a valid mobile number")
Output:

25 Write a program to Validate email using regular expressions.


Program:
import re
s = input("Enter an email id ")

flag = re.compile("^[0-9a-z]+[.]?[1-9a-z]+[@]{1}[a-z]+[.]?[a-z]+[.]*[a-z]*")

print("Valid email id" if flag.match(s) else "Please enter a valid email id")
15

Output:

26 Write a program to Validate url using regularexpression.


Program:
import re

s = input("Enter a URL: ")

flag = re.compile(r"^(https?|ftp):\/\/[^\s\/$.?#].[^\s]*$")

print("Valid URL" if flag.match(s) else "Not a valid URL")


Output:

27 Write a program to validate integer input usingexception handling.


Program:
i = input("Enter a number ")
try:
for x in i:
if not x.isdigit():
raise Exception("Not a Number")

except Exception as e:
print(e)
else:
print("Number was entered")
16

Output:

28 Write a program to demonstrate use of IndexError.


Program:
x = list(range(10))

try:
print(x[11])
except IndexError:
print("Out of index error ")
Output:

29 Write a program to demonstrate use of ZeroDivisionError


Program:
a, b = 10, 0

try:
print(a/b)
except ZeroDivisionError:
print("Cant divide by zero")
17

Output:

30 Write a program to calculate the square and cube of a number using


Multithreading.
Program:
import threading as t

def square(x):
print("Square of a number is {}".format(x*x))

def cube(x):
print("Cube of a number is {}".format(x**3))

t1 = t.Thread(target=square, args=(3,))
t2 = t.Thread(target=cube, args=(5,))

t1.start()
t2.start()

t1.join()
t2.join()
Output:

31 Write a program to print a table of two numbers using thread


synchronization.
Program:
import threading as t

def table(x):
18

for i in range(1,11):
print(f"{x} * {i} = {x*i}")

t1 = t.Thread(target= table, args=(5,))


t2 = t.Thread(target= table, args=(10,))

t1.start()
t1.join()

t2.start()
t2.join()

print("Done")
Output:

32 Write a python program to create a new file in another directory.


Program:
f = input("Enter filepath along with the name of the file ")

if open(f, "x"):
print("new file created")
19

else:
print("File already exist")
Output:

33 Write a program to copy contents from one file to another file in python.
Program:

f1 = input("Enter source file/path: ")


f2 = input("enter target file/path: ")

content=""
if open(f1,"r"):
with open(f1,"r") as file1:
content+= file1.read()
with open(f2,"w") as file2:
file2.write(content)

print("File contents copied")


file1.close()
file2.close()
Output:
20

34 Write a python program to count no. of lines in files.


Program:
f = input("Enter the file/path whose lines you want to know: ")

x= ""

with open(f,"r") as file1:


x += file1.read()

print("Total number of lines in file entered are", x.count("\n"))

Output:

35 Write a python code to create a database "dbinfo" use this sdb object to
create collection "customer" write code for: 1) insert 10 records (use
dictifields{name,cus_id,doj,address,email,mobile number,experience}) 2) select
* from "customer" 3) search records by specific name 4) delete records by
specific customer id
Program:
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["dbinfo"]
customer = mydb["customer"]

content = [{"_id" : 1,"name" : "A","cus_id": 101,"doj":


"22/07/2021","address": "asd","email": "[email protected]","mobile_number":
9876543210,"experience": 10},
{"_id" : 2,"name" : "B","cus_id": 102,"doj":
"22/07/2021","address": "qwe","email": "[email protected]","mobile_number":
9012345678,"experience": 9},
21

{"_id" : 3,"name" : "C","cus_id": 103,"doj":


"22/07/2021","address": "wer","email": "[email protected]","mobile_number":
8901234567,"experience": 8},
{"_id" : 4,"name" : "D","cus_id": 104,"doj":
"22/07/2021","address": "qws","email": "[email protected]","mobile_number":
7890123456,"experience": 7},
{"_id" : 5,"name" : "E","cus_id": 105,"doj":
"22/07/2021","address": "zxc","email": "[email protected]","mobile_number":
6789012345,"experience": 6},
{"_id" : 6,"name" : "F","cus_id": 106,"doj":
"22/07/2022","address": "ter","email": "[email protected]","mobile_number":
5678901234,"experience": 5},
{"_id" : 7,"name" : "G","cus_id": 107,"doj":
"22/07/2001","address": "wdf","email": "[email protected]","mobile_number":
4567890123,"experience": 4},
{"_id" : 8,"name" : "H","cus_id": 108,"doj":
"22/07/2011","address": "uih","email": "[email protected]","mobile_number":
3456789012,"experience": 3},
{"_id" : 9,"name" : "I","cus_id": 109,"doj":
"22/07/2031","address": "gjn","email": "[email protected]","mobile_number":
2345678901,"experience": 2},
{"_id" : 0,"name" : "J","cus_id": 110,"doj":
"12/08/2041","address": "hbf","email": "[email protected]","mobile_number":
1234567890,"experience": 1}]

x = customer.insert_many(content)
print("\nIDs of 10 inserted rows", x.inserted_ids)

print("\nselect * from customer:")


for i in customer.find():
print(i)

print("\nSearching based on customer id (108): ")


x = customer.find({"cus_id": 108})

for i in x:
print(i)

print("\nFinding based on specific name (H):")


x = customer.find({"name": "H"})

for i in x:
print(i)
Output:
22

36 Write a python program to create "doctor" collections under "dbinfo" with


the table having fields as ({doc_id,name,hosp_id,doj,speciality,salary,exp})
write a code to: 1) insert 5 records in collections 2) update exp of doctor 3)
search record after updation 4) sort documents in ascending order
Program:
import pymongo

connect = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = connect["dbinfo1"]
doctor = mydb["doctor"]

x= [
{"doc_id":1,"name":"ABC","hosp_id":1001,"doj" : "04/05/2002","speciality"
: "A","salary": 50000,"exp": 10},
{"doc_id":2,"name":"ABC","hosp_id":1001,"doj" : "04/05/2002","speciality"
: "A","salary": 40000,"exp": 10},
{"doc_id":3,"name":"ABC","hosp_id":1001,"doj" : "04/05/2002","speciality"
: "A","salary": 30000,"exp": 10},
{"doc_id":4,"name":"ABC","hosp_id":1001,"doj" : "04/05/2002","speciality"
: "A","salary": 20000,"exp": 10},
{"doc_id":5,"name":"ABC","hosp_id":1001,"doj" : "04/05/2002","speciality"
: "A","salary": 10000,"exp": 10},
23

index = doctor.insert_many(x)
print(index)

print("name set to ABC -> QWE")


newvalues = {"name": "ABC"}
setnewvalues= {"$set":{"name":"QWE"}}

doctor.update_many(newvalues,setnewvalues)

print("After Updation")
for x in doctor.find():
print(x)

doc= doctor.find().sort("salary")

print("After sorting")
for i in doc:
print(i)

Output:
24

37 Write a program using numpy to display array in theformat type of array,


dimension of array, shape of array,size of array,type of element of array arrange
the array
Program:
import numpy as np

n = np.array([1,2,3,4,5,6,7,8,9])

print(f"Type: {type(n)} || Dimension: {n.ndim} || Shape: {n.shape} || Size:


{len(n)} || Type of Element: {n.dtype}")
print(n)
Output:

38 Write a program to create numpy array and use the functions as 0's,1's,lines
space,random function and sum of array
Program:
import numpy as np

zeros = np.zeros((3,2))
ones = np.ones((2,4))
ran= np.random.random((3,10))
line = np.linspace(1,10,5)

print(f"Numpy of Zeros:\n {zeros} \nNumpy of Ones:\n {ones}\nNumpy of


linspace:\n {line}\nNumpy of Random: {ran}\nSum of Array: {np.sum(ran)}")
25

Output:

39 Write a program to create numpy arrays and use the functions as


reshape,flatten and transpose?
Program:
import numpy as np

x= np.array([1,2,3,4,5,6,7,8,9])

print(f"Original Array: {x} \nReshaped: \n{x.reshape(3,3)} \nFlattened:


{x.reshape(3,3).flatten()} \nTranspose: \n{x.reshape(3,3).transpose()}")
26

Output:

40 Write a program to save and load the array in binaryand text files
Program:
x = [1,2,3,4,5,6,7,8,9,0]

f= input("Enter file name / path to write binary in: ")

with open(f,"wb") as file:


file.write(bytes(x))

file.close()

f1= input("Enter file name of path to write decimal in: ")

with open(f1,"w") as file:


file.write(str(x)+"\n")
file.close()

print("Written in Binary and Decimal")

print("Binary file: ")


with open(f,"rb") as file:
print(file.read())
file.close()
print("Decimal file: ")
with open(f1,"r") as file:
print(file.read())

file.close()
27

Output:

41 Write a python program to create the pandas seriesfrom an array.


Program:
import pandas as pd
arr = [1,2,3,4,5,6,7]

series = pd.Series(arr)
print(f"Array: {arr} Series:\n {series}")

Output:

42 Write a python program to create the pandas seriesusing a dictionary and


specify the index.
Program:
import pandas as pd
28

d = {"A":1,"B":2,"C":3}

s = pd.Series(d)

print(f"Dictionary: {d} Series: \n{s}")


Output:

43 Write a program to access the elements of series in pandas from csv file,
also access the element from different positions
Program:
import pandas as pd
my_dict = { 'name' : ["Pranav", "Ganesh", "Venkat"],
'age' : [22,23,24],
'designation': ["Scientist", "Developer", "Army_officer"]}
df = pd.DataFrame(my_dict)
df.to_csv('python12')
df_csv = pd.read_csv('python12')
print(df_csv)

Output:

44 Write a program using pandas to the first three rowsof a given data frame
Program:
import pandas as pd
29

def display_first_three_rows(data_frame):

first_three_rows = data_frame.head(3)
print("First three rows of the DataFrame:")
print(first_three_rows)

data = {'Name': ['Pranav', 'Rohit', 'Venkat', 'Aditya'],


'Age': [22, 23, 24, 22],
'City': ['Pune', 'Latur', 'Surat', 'Delhi']}
df = pd.DataFrame(data)

display_first_three_rows(df)
Output:

45 Write a program using pandas to create and display a dataframe from a


specified dictionary data which has the index labels sample dataframe
exam_data = {"name":[choose any 10 names], "score":[10 scores],"attempts":
[10 entries],"qualify":[10 boolean values]} labels=['a','b',...10 label]
Program:
import pandas as pd
d = {"Name": ["A", "B","C","D","E","F","G","H","I","J"],
"Score": [10,10,10,10,10,10,10,10,10,10],
"attempts": [5,6,2,3,1,1,3,6,7,8],
"qualify": [True,False,True,True,True,True,True,False,False,False],
"labels": [["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
30

["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"],
["a","b","c","d","e","f","g","h","i","j"]]
}
df =pd.DataFrame(d)

print(df)
Output:

46. Write a function with list as argument and do summation of diagonal


elements of a matrix and display summation.
Program:
import numpy as np

def summation(l):
sum1, sum2 = 0,0
n = len(l)
for i in range(n):
sum1+= l[i][i]
sum2+= l[i][n-i-1]
print(f"List: \n{l}")
print(f"Sum of diagonals is {sum1} and {sum2}")

l = np.random.randint(1,100,(4,4))
summation(l)
31

Output:

47. Write a Python function that takes a dictionary as input and returns a list of
keys sorted in descending order based on their corresponding values.
Program:
l = list(input("enter the list of keys: ").split())

d = dict()

for i in l:
d[i]= int(input(f"Enter value for {i} :"))

sorting = sorted(list(d.keys()),key = lambda x : d[x])

print(f"Dictionary: {d}")
print("Keys after sorting: ", sorting)
Output:
32

48. Write a python program to copy specific elements from one tuple to a new
tuple.
Program:
t1 = (1,2,3,4,5,6,7,8,9,0)

t2 = t1[2:8]

print(f"Tuple 1: {t1} \nTuple 2: {t2}")


Output:

49. Write a python program to check if all items in the tuple are the same.
Program:
t1 = tuple(range(9,0,-1))
t2 = (1,2,3,4,5,6,7,8,9)

if sorted(t1) == sorted(t2):
print("All items of Tuple 1 are the same as Tuple 2")
else:
print("Not all elements of Tuple 1 are the same as in Tuple 2")
Output:
33

50. Write a python program to check if two sets have any elements in common.
If yes, display the common elements
Program:
def find_common_elements(set1, set2):
common_elements = set1.intersection(set2)

if common_elements:
print("Common elements found:")
for element in common_elements:
print(element)
else:
print("No common elements found.")

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

find_common_elements(set1, set2)
Output:

51. Write a python program to slice list into 3 equal chunks and reverse each
chunk.
Program:
l = [1,2,3,4,5,6,7,8,9]

s= len(l)//3

reversed_list = l[s-1::-1]+l[len(l)-s-1:s-1:-1]+l[len(l)-1:len(l)-s-1:-1]

print(f"Original list: {l} Reversed list(parted in 3): {reversed_list}")


34

Output:

52. Write a python program to remove duplicates from a list and create a tuple
and find the minimum and maximum number.
Program:
l = [1,1,1,2,3,3,3,5,5,6,7,]

print("With duplicates: ",l)


l = list(set(l))

print("Without duplicates: ",l)

t= (1,2,3,4,5)

print("Tuple: ",t,type(t), "Minimum Number in the tuple: ",min(t), "Maximum


number in the tuple: ", max(t))
Output:

53. Create a Python program that utilizes a custom package called


math_operations. The package should include two modules: basic_operations.py
for basic math operations (addition, subtraction, multiplication, division) and
advanced_operations.py for advanced math operations (exponentiation, square
root). Import both modules and demonstrate their functions in the main
program.
Program:
35

from math_operations import basic_operations as bo, advanced_operations as ao

x = int(input("Enter number 1: "))


y = int(input("Enter number 2: "))

print(f"Addition: {bo.addition(x,y)}\nSubtraction: {bo.subtraction(x,y)}\


nMultiplication: {bo.multiplication(x,y)}\nDivision: {bo.division(x,y)}")

print(f"Number1 raised to Number2: {ao.exponent(x,y)}\nSquare Root of number


1: {ao.sqaure_root(x)}")

basic_operations.py
def addition(a,b):
return a+b

def subtraction(a,b):
return a-b

def multiplication(a,b):
return a*b

def division(a,b):
return a/b

advanced_operations.py
def exponent(a,b):
return a**b

def sqaure_root(a):
return a**0.5

Output:
36

54. Write a Python program that takes a string input from the user and splits it
into words, then prints each word on a separate line.
Program:
x = input("Enter a string: ")
words = x.split()
for word in words:
print(word)
Output:

55. Develop a python program to demonstrate the working of Try-Finally


Clause
Program:
number , divisor = 10, 0

try:
print(number/divisor)
except ZeroDivisionError:
print(f"Cannot divide by zero : number = {number} divisior= {divisor}")
finally:
print("Done Programming")

Output:

You might also like