0% found this document useful (0 votes)
5 views13 pages

3&4 Units Python Programs

The document contains a series of Python programming exercises covering various concepts such as list operations, matrix calculations, file handling, and class creation. Each exercise includes an aim, a code snippet, and the expected output. The content is structured into units, with examples demonstrating the practical application of Python programming techniques.

Uploaded by

msravya896
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

3&4 Units Python Programs

The document contains a series of Python programming exercises covering various concepts such as list operations, matrix calculations, file handling, and class creation. Each exercise includes an aim, a code snippet, and the expected output. The content is structured into units, with examples demonstrating the practical application of Python programming techniques.

Uploaded by

msravya896
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit-3

Aim: Write a Python program to add each element of list x with list y using nested loops.
Program:
x = [1, 2, 3]
y = [4, 5, 6]
result = []
for i in range(len(x)):
sum_value = x[i] + y[i]
result.append(sum_value)
print("Resultant list after addition:", result)
Output: Resultant list after addition: [5, 7, 9]

Aim: Write a Python program to print the index at which a particular value exists. If the value
exists at multiple locations in the list, print all the indices and count the number of times that
value is repeated in the list.
Program:
my_list = [1, 2, 3, 2, 4, 2, 5]
value = 2
indices = []
count = 0
for i in range(len(my_list)):
if my_list[i] == value:
indices.append(i)
count += 1
print("Value", value, "exists at indices:", indices)
print("Count of", value, "in the list is:", count)
Output:
Value 2 exists at indices: [1, 3, 5]
Count of 2 in the list is: 3

Aim: Write a python program applying all the list methods ('append', 'clear', 'copy', 'count',
'extend', 'index', 'insert','pop', 'remove', 'reverse', 'sort') on the given list.
List = [100,’a’,’b’,102,2.3,4.5].

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


Program:
list=[100,'a','b',102,2.3,4.5]
print('list before append:',list)
#append
list.append('hello')
print('list after append:',list)
#count
print('no of times the value appears:',list.count(100))
#extend
list.extend(['apple','mango'])
print('list after extend:',list)
#copy
list1=list.copy()
print('list copied to list1:',list1)
#insert
list.insert(3,45)
print('list after insertion:',list)
#index
print('index no of particular item in the list:',list.index('apple'))
#sort
list2=[20,3,45,68,1,5,37]
list2.sort()
print('list after sorting:',list2)
#reverse
list2.reverse()
print('list after reverse operation:',list2)
#pop
list2.pop(4)
print('list after pop operation:',list2)
#remove
list2.remove(37)
print('list after remove operation:',list2)
list2.clear()

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


print('list after clear:',list2)
Output:
list before append: [100, 'a', 'b', 102, 2.3, 4.5]
list after append: [100, 'a', 'b', 102, 2.3, 4.5, 'hello']
no of times the value appears: 1
list after extend: [100, 'a', 'b', 102, 2.3, 4.5, 'hello', 'apple', 'mango']
list copied to list1: [100, 'a', 'b', 102, 2.3, 4.5, 'hello', 'apple', 'mango']
list after insertion: [100, 'a', 'b', 45, 102, 2.3, 4.5, 'hello', 'apple', 'mango']
index no of particular item in the list: 8
list after sorting: [1, 3, 5, 20, 37, 45, 68]
list after reverse operation: [68, 45, 37, 20, 5, 3, 1]
list after pop operation: [68, 45, 37, 20, 3, 1]
list after remove operation: [68, 45, 20, 3, 1]
list after clear: []

Aim: Write a Python program to add each element of x list with each element of y list using
loops.
Program:
x = [1, 2]
y = [3, 4]
result = []
for i in x:
for j in y:
result.append(i + j)
print("Resultant list after addition:", result)
Output:
Resultant list after addition: [4, 5, 5, 6]

Aim: Write a Python program to add each element of x list with each element of y list using list
comprehension.
Program:
x=[1,3]
y=[4,5]

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


z=[i+j for i in x for j in y]
print(z)
Output:
[5, 6, 7, 8]

Aim: Write a Python program to perform addition, subtraction, and multiplication of matrices.
Program:
X = [[1, 2], [3, 4]]
Y = [[5, 6], [7, 8]]
# You can try this in normal loops but for practice of list comprehension we tried on list
comprehensions
# Addition
result_add = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]
print("Matrix Addition:", result_add)

# Subtraction
result_sub = [[X[i][j] - Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]
print("Matrix Subtraction:", result_sub)

# Multiplication
result_mul = [[sum(X[i][k] * Y[k][j] for k in range(len(X[0]))) for j in range(len(Y[0]))] for i in
range(len(X))]
print("Matrix Multiplication:", result_mul)

Output:
Matrix Addition: [[6, 8], [10, 12]]
Matrix Subtraction: [[-4, -4], [-4, -4]]
Matrix Multiplication: [[19, 22], [43, 50]]

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


Aim: Write a Python program to create tuples (name, age, address, college) for at least two
members, concatenate them,and print the concatenated tuples.
Program:
student1 = ("John", 22, "123 Street", "NRI College")
student2 = ("Jane", 21, "456 Avenue", "NRI College")
concatenated_tuple = student1 + student2
print("Concatenated tuple:", concatenated_tuple)
Output:
Concatenated tuple: ('John', 22, '123 Street', 'NRI College', 'Jane', 21, '456 Avenue', 'NRI
College')

Aim: Write a Python program to count the number of vowels in a string without using control
flow.
Program:
string = "Hello World"
vowels = 'aeiouAEIOU'
count=0
for i in string:
if i in vowels:
count+=1
print("Number of vowels:", count)
Output:
Number of vowels: 3

Aim: Write a Python program to check if a given key exists in a dictionary.


Program:
my_dict = {"name": "John", "age": 22}
key = "name"
if key in my_dict:
print(f"Key '{key}' exists in the dictionary.")
else:

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


print(f"Key '{key}' does not exist in the dictionary.")
Output:
Key 'name' exists in the dictionary.

Aim: Write a Python program to add a new key-value pair to an existing dictionary.
Program:
my_dict = {"name": "John", "age": 22}
print("Before dictionary update:",my_dict)
my_dict["address"] = "123 Street"
my_dict["college"]="NRI"
print("Updated dictionary:", my_dict)
Output:
Before dictionary update: {'name': 'John', 'age': 22}
Updated dictionary: {'name': 'John', 'age': 22, 'address': '123 Street', 'college': 'NRI'}

Aim: Write a Python program to sum all the items in a given dictionary.
Program:
my_dict = {"a": 10, "b": 20, "c": 30}
total=0
for i in my_dict.values():
total+=i
print("Sum of all items in the dictionary:", total)
Output:
Sum of all items in the dictionary: 60

Aim: Write a Python program that reads a string from the user and creates a dictionary with the
key as word length and value as the count of words of that length.
Program:
string = "A fat cat is on the mat"
words = string.split()
print("String after splitiing:",words)
print("length of splitted string:",len(words))
length_dict = {}

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


for word in words:
length = len(word)
if length in length_dict:
length_dict[length] += 1
else:
length_dict[length] = 1
print("Dictionary of word lengths:", length_dict)
Output:
String after splitiing: ['A', 'fat', 'cat', 'is', 'on', 'the', 'mat']
length of splitted string: 7
Dictionary of word lengths: {1: 1, 3: 4, 2: 2}

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


Unit-4
Aim: Write a program to sort words in a file and put them in another file. The output file should
have only lower-case words, so any upper-case words from source must be lowered.
Program:
def sort_words(input_file, output_file):
with open('C:\\Users\\GOPAL\\Desktop\\data.txt', 'r') as f:
words = f.read().lower().split()
sorted_words = sorted(words)
with open('C:\\Users\\GOPAL\\Desktop\\output.txt', 'w') as f:
for word in sorted_words:
f.write(word + '\n')
# Usage
sort_words('data.txt', 'output.txt')
Output:
data.txt: HI HELLO WORLD HOW ARE YOU
output.txt:
are
hello
hi
how
world
you

Aim: Write a Python program to print each line of a file in reverse order.
Program:
def print_reverse(file_name):
with open("C:\\Users\\GOPAL\\Desktop\\file.txt", 'r') as f:
lines = f.readlines()
for line in reversed(lines):
print(line.strip()[::-1])
# Usage
print_reverse('file.txt')
Output: UOY ERA WOH DLROW OLLEH IH

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


Aim: Write a Python program to compute the number of characters, words and lines in a file.
Program:
def count_file_stats(file_name):
with open('C:\\Users\\GOPAL\\Desktop\\file.txt', 'r') as f:
lines = f.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"Lines: {num_lines}, Words: {num_words}, Characters: {num_chars}")
# Usage
count_file_stats('file.txt')
Output:
Lines: 1, Words: 6, Characters: 26

Aim: Write a function lines_count() that reads lines from a text file named 'zen.txt' and displays
the lines that begin with any vowel. Assume the file contains the following text and already
exists on the computer's disk:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Program:
def lines_count():
vowels = 'AEIOUaeiou'
with open('C:\\Users\\GOPAL\\Desktop\\zen.txt', 'r') as f:
lines = f.readlines()
for line in lines:
if line[0] in vowels:
print(line.strip())
# Usage
lines_count()
Output:
Explicit is better than implicit.

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


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 ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def perimeter(self):
return self.a + self.b + self.c
def area(self):
s = self.perimeter() / 2

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
# Usage example
circle = Circle(5)
print("Area of the circle is:",circle.area())
print("perimeter of the circle:",circle.perimeter())

Output:
Area of the circle is: 78.53981633974483
perimeter of the circle: 31.41592653589793

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


Aim: Write the complete code for Bank Account class based on the description given below:
Create a Python class called Bank Account which represents a bank account, having as
attributes: account Number (numeric type),
Name (name of the account owner as string type), balance.
Create a constructor with parameters: account Number, name, balance
Create a Deposit()method which manages the deposit actions.
Create a Withdrawal( ) method which manages withdrawals actions.
Create a bankFees()method to apply the bank fees with a percentage of 5% of the balance
account.
Create a display()method to display account details.
Program:
class BankAccount:
def __init__(self, account_number, name, balance):
self.account_number = account_number
self.name = name
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdrawal(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient funds.")
def bank_fees(self):
self.balance -= self.balance * 0.05
def display(self):
print(f"Account Number: {self.account_number}")
print(f"Name: {self.name}")
print(f"Balance: {self.balance}")
# Usage example
account = BankAccount(123456, "John Doe", 1000)
account.deposit(500)

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT


account.withdrawal(200)
account.bank_fees()
account.display()

Output:
Account Number: 123456
Name: John Doe
Balance: 1235.0

P.VENUGOPAL, ASSOCIATE PROFESSOR, DEPARTMENT OF CSD, NRIIT

You might also like