Pythonjornal
Pythonjornal
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:
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:
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:
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
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()))
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:
s1 = student()
Output:
def display(self):
print(f"Name: {self.name} Age: {self.age} Division: {self.div}
Standard: {self.std}")
s1.display()
s2.display()
s3.display()
Output:
7
def addition(self):
return self.a+self.b
n1= add(30,20)
print("addition of 10 and 20 is ",n1.addition())
Output:
def __del__(self):
print("Destructor called")
d= demo()
Output:
8
x = h()
y = h()
print(x.a, y.a)
Output:
demo.display = classmethod(demo.display)
demo.display()
Output:
class B(A):
def __init__(self) -> None:
super().__init__()
print("B's contructor was called")
b = B()
Output:
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
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)
o1 = SP()
o1.amount()
Output:
def display(self):
print("Current Balance",self.balance)
bank = Bank(500)
bank.deposit(400)
bank.withdraw(100)
bank.display()
Output:
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
import re
s = re.sub(r"\s+","",s)
print(s)
14
Output:
flag = re.compile("^[976]{1}[0-9]{9}")
if flag.match(s):
print("Valid mobile number")
else:
print("not a valid mobile number")
Output:
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:
flag = re.compile(r"^(https?|ftp):\/\/[^\s\/$.?#].[^\s]*$")
except Exception as e:
print(e)
else:
print("Number was entered")
16
Output:
try:
print(x[11])
except IndexError:
print("Out of index error ")
Output:
try:
print(a/b)
except ZeroDivisionError:
print("Cant divide by zero")
17
Output:
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:
def table(x):
18
for i in range(1,11):
print(f"{x} * {i} = {x*i}")
t1.start()
t1.join()
t2.start()
t2.join()
print("Done")
Output:
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:
content=""
if open(f1,"r"):
with open(f1,"r") as file1:
content+= file1.read()
with open(f2,"w") as file2:
file2.write(content)
x= ""
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"]
x = customer.insert_many(content)
print("\nIDs of 10 inserted rows", x.inserted_ids)
for i in x:
print(i)
for i in x:
print(i)
Output:
22
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)
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
n = np.array([1,2,3,4,5,6,7,8,9])
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)
Output:
x= np.array([1,2,3,4,5,6,7,8,9])
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]
file.close()
file.close()
27
Output:
series = pd.Series(arr)
print(f"Array: {arr} Series:\n {series}")
Output:
d = {"A":1,"B":2,"C":3}
s = pd.Series(d)
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)
display_first_three_rows(df)
Output:
["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:
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} :"))
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]
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]
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,]
t= (1,2,3,4,5)
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:
try:
print(number/divisor)
except ZeroDivisionError:
print(f"Cannot divide by zero : number = {number} divisior= {divisor}")
finally:
print("Done Programming")
Output: