padhublog
Thursday, September 18, 2025
Tuesday, April 1, 2025
Unit-5 programs
Program-1:
Aim: Python program to check
whether a JSON string contains complex object or not.
Program:
import json
def
has_complex_object(json_str):
try:
data=json.loads(json_str)
for value in data.values():
if isinstance(value,(list,dict)):
return True
return False
except json.JSONDecodeError:
return False
json_str1='{"name":"ravi","age":30,"city":"vijayawada"}'
json_str2='{"name":"kumar","age":25,"contact":{"email":"ravi@gmail.com","phone":"8273672682"}}'
print(has_complex_object(json_str1))
print(has_complex_object(json_str2))
program-2:
Aim: Python program to demonstrate
Numpy arrays creation using array() function.
Program:
import numpy
as np
def create_numpy_array():
arr=np.array([1,2,3,4,5])
return arr
arr=create_numpy_array()
print("Numpy
Array:",arr)
Program-3:
Aim: Python program to demonstrate
use of ndim, shape, size, dtype in Numpy array.
Program:
import numpy
as np
def
numpy_array_properties():
arr=np.array([[1,2,3],[4,5,6]])
print("Array:")
print(arr)
print("Number of
dimensions:",arr.ndim)
print("Shape(rows,columns):",arr.shape)
print("Size(total number of
elements)",arr.size)
print("Data type of
elements:",arr.dtype)
numpy_array_properties()
Program-4:
Aim: Python program to demonstrate
basic slicing, integer and Boolean indexing.
Program:
import numpy
as np
def
numpy_array_operations():
arr=np.array([1,2,3,4,5])
print("Slicing examples:")
print(arr[1:4])
print(arr[:3])
print(arr[2:])
print("\n Integer indexing:")
print(arr[[0,2,4]])
print("\nBoolean indexing:")
print(arr[arr>2])
numpy_array_operations()
Program-5:
Aim: Python program to find min,
max, sum, cumulative sum of array using Numpy.
Program:
import
numpy as np
def
numpy_array_stats():
arr=np.array([1,2,3,4,5])
print("Array:",arr)
print("Minimum
value:",np.min(arr))
print("Maximum value:",np.max(arr))
print("Sum of array
elements:",np.sum(arr))
print("Cumulative sum of array
elements:",np.cumsum(arr))
numpy_array_stats()
Program-6:
Aim: Create a dictionary, convert
it to a pandas DataFrame, and explore
data.
Program:
import pandas
as pd
def
create_dataframe_from_dict():
data = {
'Name': ['rahul', 'ravi', 'vamsi',
'sai', 'venu'],
'Age': [21, 22, 23, 24, 25],
'City': ['vijayawada', 'kondapalli',
'Mylavaram', 'IBM', 'Konduru'],
'Salary': [800000, 700000, 800000,
400000, 800000] # Corrected length
}
df = pd.DataFrame(data)
return df
df =
create_dataframe_from_dict()
print("Head
of DataFrame:")
print(df.head())
print("\nData
selection operations:")
print("Selecting
column 'Name':")
print(df['Name'])
print("\nFiltering
based on age > 22:")
print(df[df['Age']
> 22])
Tuesday, March 11, 2025
python unit-4
Unit-4 programs
Program-1:
Aim: Write a python program to sort words in a file and put them in another
file. The output file should have only lowercase words, so any uppercase words
from source must be lowered.
Program:
def
sort_words(input_file,output_file):
with open(input_file,'r') as file:
words=file.read().split()
words=sorted([word.lower() for word in
words])
with open(output_file,'w') as file:
file.write("\n".join(words))
input_file='input.txt'
output_file='output.txt'
sort_words(input_file,output_file)
print(f"words
sorted and saved to'{output_file}'")
output:
Program-2:
Aim: Python program to print each line of a file in reverse order.
Program:
def
reverse_lines(input_file):
with open(input_file,'r')as file:
lines=file.readlines()
for line in reversed(lines):
print(line.rstrip())
input_file='input.txt'
reverse_lines(input_file)
output:
Program-3:
Aim: Python program to compute the number of characters, words and lines in a
file.
Program:
def
count_chars_words_lines(input_file):
with open(input_file,'r')as file:
lines=file.readlines()
num_lines=len(lines)
num_words=sum(len(line.split())for line in
lines)
num_chars=sum(len(line)for line in lines)
print(f"Number of
lines:{num_lines}")
print(f"Number of
words:{num_words}")
print(f"Number of
characters:{num_chars}")
input_file='input.txt'
count_chars_words_lines(input_file)
output:
Program-4:
Aim: Write a program to create, display, append, insert and reverse the order
of the items in the array.
Program:
class
ArrayOperations:
def __init__(self):
self.array=[]
def create_array(self,elements):
self.array=elements
def display_array(self):
print("Array:",self.array)
def append_element(self,element):
self.array.append(element)
def insert_element(self,index,element):
self.array.insert(index,element)
def reverse_array(self):
self.array.reverse()
arr=ArrayOperations()
arr.create_array([1,2,3,4,5])
arr.display_array()
arr.append_element(6)
arr.display_array()
arr.insert_element(2,10)
arr.display_array()
arr.reverse_array()
arr.display_array()
output:
Program-5:
Aim: Write a program to add, transpose, and multiply two matrices.
Program:
matrix1 = [[1,
2, 3],[4, 5, 6],[7, 8, 9]]
matrix2 = [[9,
8, 7],[6, 5, 4],[3, 2, 1]]
add_r=[[matrix1[i][j]
+ matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))]
transpose_r=[[matrix1[j][i]
for j in range(len(matrix1))] for i in range(len(matrix1[0]))]
multiply_r=[[sum(matrix1[i][k]
* matrix2[k][j] for k in range(len(matrix1[0]))) for j in
range(len(matrix2[0]))] for i in range(len(matrix1))]
print("Matrix
Addition:")
for row in
add_r:
print(row)
print("\nMatrix
Transpose:")
for row in
transpose_r:
print(row)
print("\nMatrix
Multiplication:")
for row in
multiply_r:
print(row)
output:
Program-6:
Aim: Write a python program to create a class that represents a shape.
Include methods to calculate its area and perimeter. Implement subclasses for
different shapes like circle, triangle, and square.
Program:
import math
class Shape:
def area(self):
pass
def perimeter(self):
pass
class
Circle(Shape):
def __init__(self,radius):
self.radius=radius
def area(self):
return math.pi*self.radius
class
Triangle(Shape):
def __init__(self,base,height,side1,side2):
self.base=base
self.height=height
self.side1=side1
self.side2=side2
def area(self):
return 0.5*self.base*self.height
def perimeter(self):
return self.base+self.side1+self.side2
class
Square(Shape):
def
__init__(self,side):
self.side=side
def area(self):
return self.side**2
def perimeter(self):
return 4*self.side
circle=Circle(5)
print("Circle
Area:",circle.area())
print("Circle
Perimeter:",circle.perimeter())
triangle=Triangle(3,4,5,5)
print("\n
Triangle Area:",triangle.area())
print("Triangle
Perimeter:",triangle.perimeter())
square=Square(4)
print("\nSquare
Area:",square.area())
print("Square
Perimeter:",square.perimeter())
output:
Tuesday, February 18, 2025
python unit-3 programs
Program-1:
Aim: Write a program to create tuples
(name, age, address, college) for at least two members and concatenate the
tuples and print the concatenated tuples.
Program:
t1=('revanth',19,'vijayawada','LBRCE
college')
t2=('kumar',20,'mylavaram','CMR
college')
con_tuple=t1+t2
print(con_tuple)
output:
program-2:
Aim: Write a program to count the number
of vowels in a string (No control flow allowed).
Program:
string="pythonprogramming"
vowel_count=len([char
for char in string if char in 'aeiouAEIOU'])
print(vowel_count)
output:
program-3:
Aim : Write a program to check
if a given key exists in a dictionary or not.
Program:
dict={'a':1,'b':2,'c':3}
check='b'
exists=check
in dict
print(exists)
output:
program-4:
Aim: Write a program to add a new key-value
pair to an existing dictionary
Program:
dict={'a':1,'b':2}
dict['c']=3
print(dict)
output:
program-5:
Aim: Write a program to sum all the items
in a given dictionary.
Program:
dict={'a':10,'b':20,'c':30}
total_sum=sum(dict.values())
print(total_sum)
output:
pyhton unit-2 programs
Program-1:
Aim: Write a python program to define a
function with multiple return values.
Program:
def
operations(x,y):
sum=x+y
sub=x-y
mul=x*y
return sum,sub,mul
sum,sub,mul=operations(25,15)
print("sum:",sum)
print("sub:",sub)
print("mul:",mul)
Output:
(Or)
def
operations(x,y):
sum=x+y
sub=x-y
mul=x*y
return sum,sub,mul
sum,sub,mul=operations(25,15)
print("sum:",sum)
print("sub:",sub)
print("mul:",mul)
program-2:
Aim: Write a python program to define a
function using default arguments.
Program:
def
defaultArgs(a=10,b=15,c=30):
print(a,b,c)
return
defaultArgs()
Output:
(or)
def
area_rect(height=1,length=1):
area=height*length
print(area)
area_rect(10,10)
output:
Program-3:
Aim: Write a python program to find the length of the
string without using any library functions.
Program:
string=input("Enter
the string:")
count=0
for i in
string:
count=count+1
print("Length
of the given string is: ", count)
Output:
Program-4:
Aim: Write a python program to check if
the substring is present in the given string.
Program:
s1=input("Enter
String:")
s2=input("Enter
Sub_string:")
if(s1.find(s2)==-1):
print("Sub_string not found in
s1.")
else:
print("Sub_string in s1.")
output:
Enter String:hai
python programming
Enter
Sub_string:python
Sub_string
in s1.
Program-5:
Aim: Write a python program to perfrom
the given operations on a list.
1)Addition
2)insertion 3)slicing
Program:
list = [10,
20, 30, 40, 50]
print("Actual
list:",list)#Initialize
list.append(60)
print("After
addition:",list)# Addition
list.insert(2,
25)
print("After
insertion:",list)# Insertion
sublist =
list[1:4]
print("Sliced
list:", sublist)#Slicing
output:
Program-6:
Aim: Write a python program to perform any
5 built-in functions by taking any list.
Program:
list=[10,20,30,40,50]
print("Acutal:",list)
list.append(60)
print("After
append:",list)
list.remove(20)
print("After
remove:",list)
pop=list.pop()
print("pop
element:",pop)
print("After
pop:",list)
list.sort()
print("After
sort:",list)
list.reverse()
print("After
reverse:",list)
output:
python unit-1 programs
Program 1:
Aim: Write a python program to find the
largest element among three Numbers
Program:
a=int(input("Enter
a value :"))
b=int(input("Enter
b value :"))
c=int(input("Enter
c value :"))
if((a>b)&(a>c)):
print("a is big",a)
elif(b>c):
print("b is big",b)
else:
print("c is big",c)
Output:
Program 2:
Aim: Write a python program for all prime
numbers with in range.
Program:
min=int(input("Enter
min number"))
max=int(input("Enter
max number"))
for i in
range(min,max):
count=0
for j in range(1,i+1):
if(i%j==0):
count+=1
if(count==2):
print(i)
Output:
Program 3:
Aim: Write a python program to swap two
numbers without using a temporary variable.
Program:
a,b=10,20
a,b=b,a
print(a,b)
output:
Program 4.1:
Aim: Demonstrate the following Operators
in python with examples
a Arithmetic Operators
Program:
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a//b=",a//b)
print("a**b=",a**b)
Output:
Program 4.2:
Aim: Demonstrate the following Operators
in python with examples
b Relational Operators
Program:
a=10
b=20
print("a<b=",a<b)
print("a>b=",a>b)
print("a<=b=",a<=b)
print("a>=b=",a>=b)
print("a==b=",a==b)
print("a!=b=",a!=b)
Output:
Program 4.3:
Aim: Demonstrate the following Operator
in python with examples
c)Assignment Operators:
Program:
#1. = (Simple Assignment)
x = 10
print(x)
#2. += (Addition Assignment)
x = 10
x += 5
print(x)
#3. -= (Subtraction Assignment)
x = 10
x -= 3
print(x)
#4. *= (Multiplication Assignment)
x = 4
x *= 2
print(x)
#5. /= (Division Assignment)
x = 20
x /= 4
print(x)
#6. //= (Floor Division Assignment)
x = 20
x //= 3
print(x)
#7. %= (Modulus Assignment)
x = 2
x **= 3
print(x)
#9. &=, |=, ^=, <<=,
>>= (Bitwise Assignment Operators)
x = 10
x &=
4
print(x)
x = 10
x |= 4
print(x)
x = 10
x ^= 4
print(x)
x = 10
x <<=
2
print(x)
x = 10
x >>=
2
print(x)
Output:
Program 4.4:
Aim: Demonstrate the following Operator
in python with examples
d)Logical Operators:
Program:
x = 5
y = 10
# Both conditions must be true for
the result to be true
result = (x
> 3) and (y < 20)
print(result)
result = (x
> 3) and (y > 20)
print(result)
# At least one condition must be true
for the result to be true
result = (x
> 3) or (y > 20)
print(result)
result = (x
< 3) or (y > 20)
print(result)
x = 5
# The not operator reverses the
result
result = not
(x > 3)
print(result)
result = not
(x < 3)
print(result)
Output:
Program 4.5:
Aim: Demonstrate the following Operator
in python with examples
e)Bit Wise Operators:
Program:
a=5
b=3
print("a&b=",a&b)
print("a|b=",a|b)
print("a^b=",a^b)
print("~a",~a)
print("a<<1=",a<<1)
print("a>>1=",a>>1)
Output:
Program 4.6:
Aim: Demonstrate the following Operator
in python with examples
f)Ternary Operators:
Program:
#Basic Ternary Operator
x = 10
result =
"Even" if x % 2 == 0 else "Odd"
print(result)
#Using Ternary Operator to Assign a Value
age = 18
status =
"Adult" if age >= 18 else "Minor"
print(status)
#Nested Ternary Operator
x = 5
y = 10
result =
"x is greater" if x > y else "x is equal to y" if x == y
else "x is less"
print(result)
# Using Ternary Operator with
Functions
def check_number(num):
return "Positive" if num > 0
else "Negative" if num < 0 else "Zero"
print(check_number(10))
print(check_number(-5))
print(check_number(0))
#Assigning Multiple Values
x = 15
y = 10
a, b =
("x is greater", "y is greater") if x > y else ("y
is greater", "x is greater")
print(a,
b)
Output:
Program 4.7:
Aim: Demonstrate the following Operator
in python with examples
g)Membership Operators:
Program:
#Using in
Operator
fruits =
["apple", "banana", "cherry"]
print("banana"
in fruits)
print("orange"
in fruits)
#Using not
in Operator
fruits =
["apple", "banana", "cherry"]
print("orange"
not in fruits)
print("banana"
not in fruits)
Output:
Program 4.8:
Aim: Demonstrate the following Operator
in python with examples
h)Identity Operators:
Program:
#Using is Operator
a = 5
b = 5
print(a is
b)
#Using is not Operator
a = 10
b = 20
print(a is
not b)
Output:
Program 5:
Aim: Write a python program to add and
multiply complex numbers
Program:
n1=complex(3,4)
n2=complex(1,2)
addr=n1+n2
print("Addcomplex+",addr)
mulr=n1*n2
print("Multiplycomplex+",mulr)
Output:
Program 6:
Aim: Write a python program to print
multiplication table of a given number
Program:
num =
int(input("Enter a number: "))
for i in
range(1, 11):
print(f"{num} x {i} = {num * i}")
Output:
-
Unit-4 programs Program-1: Aim: Write a python program to sort words in a file and put them in another file. The output file should have...
-
Program 1: Aim: Write a python program to find the largest element among three Numbers Program: a=int(input("Enter a value :...
-
Program-1: Aim: Write a python program to define a function with multiple return values. Program: def operations(x,y): sum=x+...