0% found this document useful (0 votes)
49 views22 pages

Practical Main

1. A list containing city names is defined. 2. The list is written to a binary file using a with statement. 3. The binary file is then opened and read. 4. The contents of the file (the list) are displayed.

Uploaded by

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

Practical Main

1. A list containing city names is defined. 2. The list is written to a binary file using a with statement. 3. The binary file is then opened and read. 4. The contents of the file (the list) are displayed.

Uploaded by

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

COMPUTER

PRACTICAL
FILE

NAME – SHREYAS
THAKUR
CLASS – XII – C
ROLL NO. - 40
Shreyas 12-C
#Determine whether a number is a perfect number, an Armstrong number or a
palindrome.

INPUT
num = int(input("Enter a number: "))
sum = 0

temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

OUTPUT

Enter a number: 407


407 is an Armstrong number

Input a number and check if the number is a prime or composite number.

INPUT

num = int(input("Enter a number: "))


flag = False
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

OUTPUT:

29 is a prime number
#SHREYAS
Display the terms of a Fibonacci series.

nterms = int(input("How many terms? "))

n1, n2 = 0, 1
count = 0

if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

OUTPUT:

How many terms? 7


Fibonacci sequence:
0
1
1
2
3
5
8

Compute the greatest common vow and least common multiple of two
integers.

INPUT

num1 = int(input('Enter your first number: '))


num2 = int(input('Enter your second number: '))
def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm
print("The L.C.M. is", compute_lcm(num1, num2))

OUTPUT:

Enter your first number: 18


Enter your second number: 6
The L.C.M. is18

#SHREYAS
Count and display the number of vowels, consonants, uppercase, lowercase
characters in string.

INPUT

Str="GeeksForGeeks"
lower=0
upper=0
for i in Str:
if(i.islower()):
lower+=1
else:
upper+=1
print("The number of lowercase characters is:",lower)
print("The number of uppercase characters is:",upper)

OUTPUT:

The number of lowercase characters is: 10


The number of uppercase characters is: 3
#SHREYAS
Input a string and determine whether it is a palindrome or not; convert the
case of characters in a string.

INPUT
my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

OUTPUT:

The string is a palindrome.

#SHREYAS
Find the largest/smallest number in a list/tuple

INPUT

lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :",
min(lst))

OUTPUT:

How many numbers: 6


Enter number 19
Enter number 29
Enter number 25
Enter number 62
Enter number 57
Enter number 1
Maximum element in the list is :62
Minimum element in the list is :1
#SHREYAS
Input a list of numbers and swap elements at the even location with the
elements at the odd location.

def solve(self, nums):


length = len(nums)
for i in range(0,length,4):
if(i+2<length):
nums[i], nums[i+2] = nums[i+2], nums[i]
if(i+3<length):
nums[i+1], nums[i+3] = nums[i+3], nums[i+1]
return nums
nums = [1,2,3,4,5,6,7,8,9]
print(solve(nums))

OUTPUT:

[3, 4, 1, 2, 7, 8, 5, 6, 9]

Input a list/tuple of elements, search for a given element in the list/tuple.

INPUT

Input = [(11, 22), (33, 55), (55, 77),


(11, 44), (33, 22, 100, 11), (99, 11)]

x = 11
Output = []
for i in Input:
if x in i:
Output.append(i)
# Printing output
print(Output)

OUTPUT:

[(11, 22), (11, 44), (33, 22, 100, 11), (99, 11)]
Create a dictionary with the roll number, name and marks of n students in a
class and display the names of students who have marks above 75.

INPUT

no_of_std = int(input("Enter number of students: "))


result = {}
for i in range(no_of_std):
print("Enter Details of student No.", i+1)
roll_no = int(input("Roll No: "))
std_name = input("Student Name: ")
marks = int(input("Marks: "))
result[roll_no] = [std_name, marks]
print(result)
for student in result:
if result[student][1] > 75:
print("Student's name who get more than 75 marks is/are",(result[student][0]))

OUTPUT:

Enter number of students: 5


('Enter Details of student No.', 1)
Roll No: 1
Student Name: "Amit"
Marks: 78
('Enter Details of student No.', 2)
Roll No: 2
Student Name: "Abhay"
Marks: 78
('Enter Details of student No.', 3)
Roll No: 3
Student Name: "Pooja"
Marks: 76
('Enter Details of student No.', 4)
Roll No: 4
Student Name: "Aarti"
Marks: 60
('Enter Details of student No.', 5)
Roll No: 5
Student Name: "Harshit"
Marks: 55
{1: ['Amit', 78], 2: ['Abhay', 78], 3: ['Pooja', 76], 4: ['Aarti', 60], 5: ['Harshit', 55]}
("Student's name who get more than 75 marks is/are", 'Amit')
("Student's name who get more than 75 marks is/are", 'Abhay')
("Student's name who get more than 75 marks is/are", 'Pooja')
#SHREYAS #ABHISHEK #ZAID

INPUT:
import math
x =int(input('Enter Value of x:'))
n=int(input('Enter Value of n:'))
result=0
for i in range(n+1):
result+=x**i
print()
print('First Case')
print (result)
result = 0
sign = 1
for i in range(n + 1):
result += sign * (x ** i)
sign *= -1
print()
print('Second Case')
print(result)
result = 0
for i in range(1, n + 1):
result += (x ** i) / i
print()
print('Third Case')
print(result)
result = 0
for i in range(1, n + 1):
result += (x ** i) / math.factorial(i)
print()
print('Fourth Case')
print(result)

OUTPUT:

Enter Value of x:3


Enter Value of n:3

First Case
40

Second Case
-20

Third Case
16.5

Fourth Case
12.0

#SHREYAS
#Determine whether a number is a perfect number, an Armstrong number or a
palindrome.

INPUT:

number = int(input("Enter a number: "))


divisors_sum = 0
for i in range(1, number):
if number % i == 0:
divisors_sum += i
is_perfect = divisors_sum == number
num_str = str(number)
num_len = len(num_str)
armstrong_sum = 0
for digit in num_str:
armstrong_sum += int(digit) ** num_len
is_armstrong = armstrong_sum == number
num_str_reversed = num_str[::-1]
is_palindrome = num_str == num_str_reversed
if is_perfect:
print(f"{number} is a perfect number.")
else:
print(f"{number} is not a perfect number.")
if is_armstrong:
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
if is_palindrome:
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")

OUTPUT:
Enter a number: 153
153 is not a perfect number.
153 is an Armstrong number.
153 is not a palindrome.

#SHREYAS #ABHISHEK #ZAID


#Input a string and determine whether it is a palindrome or not; convert the case of
characters in a string.

INPUT:

str1=input("Enter a string :")


def isPalindrome(str1):
str1=str1.lower()
return str1==str1[::-1]
ans=isPalindrome(str1)
if ans:
print("The given string is a Palindrome string")
else:
print("The given string is not a Palindrome string")

OUTPUT:
Enter a string :abcCBA
The given string is a Palindrome string

#WAP Read the contents of file "file. txt" (i) replace the occurences of 'e' with '@'
(ii)Count the no. of 'the' and 'these'(i) count no. of words
dont write comments explainiing the code
INPUT:

file = open('file.txt', 'r')


content = file.read()
content1 = content.replace('e', '@')

count_the = content.count('the')
count_these = content.count('these')

words = content.split()
word_count = len(words)

print("Occurrences of 'the':", count_the)


print("Occurrences of 'these':", count_these)
print("Total number of words:", word_count)
print(‘e replaced with @:’, content1)
print(content)
file.close()

OUTPUT:

Occurrences of 'the': 5
Occurrences of 'these':3
Total number of words:18
e replaced with @

#SHREYAS
#WAP to locate and update a binary file at the exact location

INPUT:

import pickle
f=open('student.dat','wb+')
mm = input ("Enter name to be updated:")
try:
While True:
pos=f.tell()
l = pickle. load (f)
if mm = l [1]:
nm_2=input("Enter new name")
l[1]=nm_2
f.seek(pos)
pickle.dump(l,f)
found=True
else:
pickle.dump(l,f)
except EOFError:
if found==True:
print("Record updated")
else:
print("Record not updated")
finally:
f.close()

OUTPUT:
Enter name to be updated: Alice
Enter new name: Alicia
Record updated

#Write a function common()which accepts two lists as arguments and returns the
common elements from both the lists list.

INPUT:
def common(l1,l2):
l=[]
if len(l1)>=len(l2):
for i in l2:
if i in l1:
l.append(i)
else:
for i in l1:
if i in l2:
l.append(i)
return l
l1,l2=[],[]
n=int(input('enter number of elements in list 1:'))
for i in range(n):
val=int(input('Enter value:'))
l1.append(val)
m=int(input('enter number of elements in list 2:'))
for i in range(m):
val=int(input('Enter value:'))
l2.append(val)
print('common elements=',common(l1,l2))

OUTPUT:
enter number of elements in list 1:3
Enter value:1
Enter value:2
Enter value:3
enter number of elements in list 2:5
Enter value:1
Enter value:3
Enter value:5
Enter value:7
Enter value:9
common elements= [1, 3]

#SHREYAS
Write into a BF, Read the contents and display - using lists

INPUT

places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']


with open('listfile.txt', 'w') as filehandle:
for listitem in places:
filehandle.write(f'{listitem}\n')
places = []

# Open the file and read the content in a list


with open('listfile.txt', 'r') as filehandle:
for line in filehandle:
curr_place = line[:-1]
places.append(curr_place)

Write into a BF, Read the contents and display - using dictionary
details={'Name' : "prakhar",
'Age' : 17,}
with open("myfile.txt", 'w') as f:
for key, value in details.items():
f.write('%s:%s\n' % (key, value))

Update and display file before and after updating – list of Employee data
(ENo,EName,Dept,Desig and Sal)

INPUT

def update_binary(word, new)


Flag = 0
with open('file.txt', 'r + b') as file:
pos = 0
data = string = file.read(1)
while data:
data = file.read(1)
if data == b" ":
if string == word:
file.seek(pos)
file.write(new)
Flag = 1
break
else:
# storing the position of
# current file pointer i.e. at
# the end of previously read record
pos = file.tell()
data = string = file.read(1)
else:
string += data
continue
if Flag:
print("Record successfully updated")
else:
print("Record not found")
word = input("Enterr the word to be replaced: ").encode()
new = input("\nEnter the new word: ").encode()
update_binary(word, new)

OUTPUT:

Enterr the word to be replaced: Paris


Enter the new word: Mumbai
Record successfully updated

Shreyas 12-c
Update and display file before and after updating – dictionary for file with
Student with StName as key and (RollNo,Cl_Sec,TotM ) as Key Values.

INPUT

def checkKey(dict, key):


if key in dict.keys():
print("Key exist, ", end =" ")
dict.update({'m':600})
print("value updated =", 600)
else:
print("Not Exist")
dict = {'m': 700, 'n':100, 't':500}
key = 'm'
checkKey(dict, key)
print(dict)

OUTPUT:

Key exist, value updated = 600


{'m': 600, 'n': 100, 't': 500}

#SHREYAS
I. Program to read data into a csv file and display the data

INPUT

import csv
with open('people.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

OUTPUT:
['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']

ii. Write data into a csv file.

INPUT

import csv
with open('protagonist.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["SN", "Movie", "Protagonist"])
writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])
writer.writerow([2, "Harry Potter", "Harry Potter"])

OUTPUT:

SN,Movie,Protagonist
1,Lord of the Rings,Frodo Baggins
2,Harry Potter,Harry Potter

#SHREYAS 12-C
Write a menu driven program to create a list of integers and perform stack
operations on it PUSH , POP and DISPLAY.

INPUT

stack = []

def push_element():
element = int(input("Enter an integer to push onto the stack: "))
stack.append(element)
print(f"{element} has been pushed onto the stack.")

def pop_element():
if not stack:
print("Stack is empty. Cannot pop.")
else:
popped_element = stack.pop()
print(f"Popped element: {popped_element}")

def display_stack():
if not stack:
print("Stack is empty.")
else:
print("Stack elements:")
for element in stack:
print(element)

while True:
print("\nStack Operations Menu:")
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
print("4. EXIT")

choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
push_element()
elif choice == '2':
pop_element()
elif choice == '3':
display_stack()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

OUTPUT:

Stack Operations Menu:


1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice (1/2/3/4): 1
Enter an integer to push onto the stack: 5
5 has been pushed onto the stack.

Stack Operations Menu:


1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice (1/2/3/4): 3
Stack elements:
5

Stack Operations Menu:


1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice (1/2/3/4): 4
Exiting the program.

#SHREYAS
Write a menu driven programme in python, Push(Vehicle), Push(Vehicle) and
Display() where, Vehicle is a dictionary containing details of vehicles –
{Car_Name:Maker).The function should push the name of car manufactured by
“TATA” ( including all the possible cases like Tata , TaTa,etc ) to the stack.

vehicle = {
"Santro": "Hyundai",
"Nexon": "TATA",
"Safari": "Tata"
}

stack = []

def push_vehicle():
for car_name, maker in vehicle.items():
if maker.lower() == "tata":
stack.append(car_name)
print(f"{car_name} has been pushed onto the stack.")

def display_stack():
if not stack:
print("Stack is empty.")
else:
print("Cars manufactured by 'TATA' in the stack:")
for car_name in reversed(stack):
print(car_name)

while True:
print("\nVehicle Operations Menu:")
print("1. Push Vehicles Manufactured by 'TATA'")
print("2. Display Vehicles in the Stack")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
push_vehicle()
elif choice == '2':
display_stack()
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

#SHREYAS

Write a function EOReplace() in Python, which accepts a list L of numbers.

Thereafter, it increments all even numbers by 1 and decrements all off number by 1.
Example: If Sample Input data of the list is:
L=[10,20,30,40,35,55]
Output will be:
L=[11,21,31,41,34,54)

def EOReplace(L):
for i in range(len(L)):
if L[i] % 2 == 0:
L[i] += 1
else:
L[i] -= 1
EOReplace(L)
print(L)

INPUT:
L = [2, 7, 8, 15, 22, 9, 14, 6, 11, 10]

OUTPUT:
L = [3, 6, 9, 14, 23, 8, 13, 7, 10, 11]

SQL – I
Q.1:
Create a table ‘student’,in a newly created database ‘12_C’

mysql>show databases;
+--------------------+
| Database |
+--------------------+
| information |
| mysql |
| performance|
| students |
| school |
| world |
+--------------------+
6 rows in set (0.02 sec)
mysql>create database 12_C;
Query OK, 1 row affected (0.01 sec)
mysql>use 12_C;
Database changed
mysql>show tables;
Empty set (0.01 sec)
mysql>create table student
->(rno int(3),
->admno varchar(5) primary key,
->name varchar(30),
->cl_sec varchar(5),
->dob date,
->tot_m int(3));
Query OK, 0 rows affected, 2 warnings (0.03 sec)
Q.2:
Add records in the table ‘student’.
(i)
mysql>insert into student values(42, '29805', ‘Abhishek', '12-C', '2006-08-31', '99');
Query OK, 1 row affected (0.01 sec)
(ii)
mysql>insert into student(admno, name,roll no)
values('25700', ‘Shreyas',38);
Query OK, 1 row affected (0.00 sec)
(iii)
mysql>insert into student values(NULL, '51287',’Zaid ,
'12-C', NULL, NULL);
Query OK, 1 row affected (0.00 sec)
Q.3:
Display the structure of the table ‘student’.
mysql>desc student;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| rno | int | YES | | NULL | |
| admno | varchar(5) | NO | PRI | NULL | |
| name | varchar(30) | YES | | NULL | |
| cl_sec | varchar(5) | YES | | NULL | |
| dob | date | YES | | NULL | |
| tot_m | int | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
Q.4:
Display all the contents of the table ‘student’.
mysql>select * from student;
+------+-------+-------------------+--------+------------+-------+
| rno | admno | name | cl_sec | dob | tot_m |
+------+-------+-------------------+--------+------------+-------+
| 38 | 25700 | Shreyas | NULL | NULL |
NULL |
| 42 | 29805 | Abhishek | 12-C | 2006-08-31 |
99 |
| NULL | 51287 | Zaid | 12-C | NULL | NULL |
+------+-------+-------------------+--------+------------+-------+
3 rows in set (0.00 sec)

Q.5
Display the roll number, name, class and section of all the
students.
mysql>select rno, name, cl_sec from student;
+------+-------------------+--------+
| rno | name | cl_sec |
+------+-------------------+--------+
| 38 | Shreyas | NULL |
| 42 | Abhishek | 12-C |
| NULL | Zaid | 12-C |
+------+-------------------+--------+
3 rows in set (0.00 sec)

Q.6:
Display the admission number, name, class and section of
all students in class in 12 – C.
mysql>select admno, name, cl_sec from student where
cl_sec = '12-C';
+-------+-------------------+--------+
| admno | name | cl_sec |
+-------+-------------------+--------+
| 29805 | Abhishek | 12-C |
+-------+-------------------+--------+
| 25700 | Shreyas | 12-C |
1 row in set (0.00 sec)
# Adding more students’ data:
(i)
mysql>insert into student values(11, '44871', 'Taksh',
'12-C', '2007-01-16', 75);
Query OK, 1 row affected (0.00 sec)
(ii)
mysql>insert into student(admno, cl_sec, tot_m)
values('98871', '12-C', 88);
Query OK, 1 row affected (0.00 sec)
(iii)
mysql>insert into student(admno, name, dob)
values('23322', 'Ranvir', '2006-08-29');
Query OK, 1 row affected (0.00 sec)
Q.7
Display roll number, name and date of birth of all the
students born after 15th October 2006.
mysql>select rno, name, dob from student where dob <
'2006-10-15';
+------+-------------+------------+
| rno | name | dob |
+------+-------------+------------+
| 11 | Taksh | 2007-01-16 |
+------+-------------+------------+
1 row in set (0.00 sec)

Q.8
Display admission number, class and section of all
students born between 15th June 2006 and 31st December
2006.
(i)
mysql>select admno, name, cl_sec from student where dob
>= '2006-06-15' and dob <= '2006-12-31';
+-------+-------------------+--------+
| admno | name | cl_sec |
+-------+-------------------+--------+
| 23322 | Ranvir | NULL |
| 29805 | Abhishek | 12-C |
+-------+-------------------+--------+
2 rows in set (0.00 sec)
(ii)
mysql>select admno, name, cl_sec from student where dob
between '2005-01-01' and '2007-01-01';
+-------+-------------------+--------+
| admno | name | cl_sec |
+-------+-------------------+--------+
| 23322 | Ranvir | NULL |
| 25700 | Shreyas | 12-C |
| 29805 | Abhishek | 12-C |
| 44871 | Taksh | 12-E |
+-------+-------------------+--------+
3 rows in set (0.00 sec)

You might also like