Taruncs 1
Taruncs 1
1) Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
'''
import random
n=random.randint(1,6)
print(n)
'''
Run code >>> py Tarun.py
O/P
4
'''
'''
2) Write a code where you use the wrong number of arguments for a method (say sqrt() or
pow()).Use the exception handling process to catch the ValueError exception.
'''
import math
a1=int(input("INPUT THE VALUE"))
try:
b1=int(input("INPUT THE VALUE"))
c=math.sqrt(b1)
d=math.pow(a1,b1)
print(c)
print(d)
except Exception as e:
print(e)
print("YOUR INPUT MUST BE A NUMBER NOT A SYMBOL,ALPHABET ETC..")
'''
Run code>>> py Tarun.py
O/P
INPUT THE VALUE 4
INPUT THE VALUE b
invalid literal for int() with base 10: 'b'
YOUR INPUT MUST BE A NUMBER NOT A SYMBOL,ALPHABET ETC..
'''
'''
3) Write a program to accept string/sentences from the user till the user enters “END” to.
Save the data in a text file and then display only those sentences which begin with an
uppercase alphabet.
1
'''
f=open("welcome.txt","w")
while True:
w_l=input("ENTER YOUR LINE, AND WRITE 'END' TO EXIT")
if w_l=="END":
break
f.write(w_l + '\n')
f.close
f=open("welcome.txt","r")
while True:
w_l=f.readline()
if not w_l:
break
if w_l[0].isupper():
print(w_l)
f.close()
'''
Run code>>> py Tarun.py
O/P
ENTER YOUR LINE, AND WRITE 'END' TO EXIT Hello world
ENTER YOUR LINE, AND WRITE 'END' TO EXIT my name is tarun
ENTER YOUR LINE, AND WRITE 'END' TO EXIT This is my project
ENTER YOUR LINE, AND WRITE 'END' TO EXIT END
Hello world
This is my project
'''
'''
4) Write a program to enter the following records in a binary file:
item_no int
item_name str
qty int
price float
Number of records to be entered should be accepted from the user. Read the file to display
the records in the following format:
Item No:
Item Name:
Quantity:
Price/Item:
Amount: (To be calculated as price * qty)
'''
2
import pickle
def write_records():
with open("items.dat", "wb") as f:
n = int(input("Enter the number of records to be entered: "))
for _ in range(n):
item_no = int(input("Enter item number: "))
item_name = input("Enter item name: ")
qty = int(input("Enter quantity: "))
price = float(input("Enter price per item: "))
def read_records():
try:
records = []
with open("items.dat", "rb") as f:
while True:
try:
record = pickle.load(f)
records.append(record)
except EOFError:
break
if records:
print("Item Records:",end='\n')
for record in records:
amount = record["qty"] * record["price"]
print(f"Item No: {record['item_no']}")
print(f"Item Name: {record['item_name']}")
print(f"Quantity: {record['qty']}")
print(f"Price/Item: {record['price']}")
print(f"Amount: {amount:}",end='\n')
else:
print("No records found.")
except FileNotFoundError:
print("ERROR: File 'items.dat' not found.")
while True:
3
print("Menu:",end='\n')
print("1. Add Records")
print("2. Display Records")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ").strip()
if choice == "1":
write_records()
elif choice == "2":
read_records()
elif choice == "3":
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter 1, 2, or 3.")
'''
Run code >>> py Tarun.py
O/P
Enter the number of records to be entered: 2
Enter item number: 101
Enter item name: BAG
Enter quantity: 10
Enter price per item: 400
Enter item number: 102
Enter item name: PENCIL BOX
Enter quantity: 15
Enter price per item: 50
Records added successfully!
Item Records:
Item No: 101
Item Name: BAG
Quantity: 10
Price/Item: 400.00
Amount: 4000.00
'''
4
'''
5)Write a program to create a Stack for storing only odd numbers out of all the numbers
entered by the user. Display the content of the Stack along with the largest odd number in
the Stack.
'''
n=int(input("ENTER THE NUMBER OF VALUES-"))
stack=[]
for i in range(n):
no=int(input("ENTER YOUR NUMBER-"))
if no%2 !=0:
stack.append(no)
lar_no=stack.pop()
while (len(stack)>0):
no=stack.pop()
if no>lar_no:
no=large_no
print()
print("THE LARGEST NUMBER IN IT IS-",lar_no)
'''
Run code>>> py Tarun.py
ENTER THE NUMBER OF VALUES-6
ENTER YOUR NUMBER-3
ENTER YOUR NUMBER-7
ENTER YOUR NUMBER-46
ENTER YOUR NUMBER-70
ENTER YOUR NUMBER-31
ENTER YOUR NUMBER-90
'''
6) Write a program to reverse a string using stack.
'''
def reverse_string(input_string):
stack = []
5
stack.append(char)
reversed_string = ""
while stack:
reversed_string += stack.pop()
return reversed_string
'''
Run code>>> py Tarun.py
Enter a string to reverse: COMPUTER SCIENCE
Reversed string: ECNEICS RETUPMOC
'''
'''
7) Write a Python program to implement a stack using list.
'''
stack=[]
def push():
ele=input("ENTER THE ELEMENT TO ADD IN STACK")
stack.append(ele)
push()
push()
'''
Run code >>> py Tarun.py
ENTER THE ELEMENT TO ADD IN STACKTARUN
['TARUN']
ENTER THE ELEMENT TO ADD IN STACKCS
['TARUN', 'CS']
'''
'''
8) Write a program using user defined functions that accepts a List of numbers as an
argument and finds its median. (Hint: Use bubble sort to sort the accepted list. If there are
odd number of terms, the median is the centre term. If there are even number of terms,
add the two middle terms and divide by 2 get median)
'''
6
def find_median(nums):
# Bubble sort
for i in range(len(nums)):
for j in range(len(nums)-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j] # Swap elements
n = len(nums)
if n % 2 != 0:
return nums[n // 2]
else:
return (nums[n // 2 - 1] + nums[n // 2]) / 2
# Main program
nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
median = find_median(nums)
print("The median is:", median)
'''
Run code >>> py Tarun.py
Enter numbers separated by spaces: 1 6 5 4 9
The median is: 5
'''
'''
9) During admission in a course, the names of the students are inserted in ascending order.
Thus, performing the sorting operation at the time of inserting elements in a list. Write a
program using a user defined function.
'''
l_of_stud=[ ]
def push():
l_of_stud.append(st)
print(l_of_stud)
push()
push()
push()
push()
asc_stu_lt =sorted(l_of_stud)
print()
7
print("THE ASCENDING ORDER OF YOUR GIVEN ITEMS ARE")
print()
print(asc_stu_lt)
'''
Run code >>> py Tarun.py
ENTER THE STUDENT NAME Tarun
[' Tarun']
ENTER THE STUDENT NAME Aayush
[' Tarun', ' Aayush']
ENTER THE STUDENT NAME Nikunj
[' Tarun', ' Aayush', ' Nikunj']
ENTER THE STUDENT NAME Devansh
[' Tarun', ' Aayush', ' Nikunj', ' Devansh']
'''
10) Write a program that takes as input a list having a mix of 10 negative and positive
numbers and a key value. Apply linear search to find whether the key is present in the list
or not. If the key is present, it should display the position of the key in the list otherwise it
should print an appropriate message. Run the program for at least 3different keys and note
the result.
'''
def linear_search(numbers, key):
for i in range(len(numbers)):
if numbers[i] == key:
return i + 1 # Return 1-based position
return -1 # Return -1 if not found
8
'''
Run code >>> py Tarun.py
Key 3 found at position 3.
Key 7 not found.
Key -11 found at position 7.
'''
'''
11) Read a text file line by line and display each word separated by a #.
'''
file_path = "rep_f.txt"
try:
file = open(file_path, 'r')
for line in file:
# Remove whitespaces
line = line.strip()
# Split the line into words and join with #
f_line = "#".join(line.split())
print(f_line)
file.close()
except Exception as e:
print(f"An error occurred: {e}")
'''
Run code >>> py Tarun.py
HELLO#EVERYONE MY#NAME#IS#TARUN THIS#IS#MY#C.S#FILE
'''
9
'''
12) Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.
'''
f_p = input("Enter the name to your text file: ")
file.writelines(l)
file.close()
try:
file = open(f_p, 'r')
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
vowels_set = set("aeiouAEIOU")
except Exception as e:
10
print(f"An error occurred: {e}")
'''
Run code >>> py Tarun.py
O/P
Number of vowels: 6
Number of consonants: 15
Number of uppercase characters: 4
Number of lowercase characters: 17
'''
'''
13) Remove all the lines that contain the character 'a' in a file and write it to another file.
'''
infile=open('input.txt', 'w')
infile.write(" I am a c.s student")
infile.close()
'''
Run code >>> py Tarun.py
O/P
lines containing 'a' have been removed and written to 'output.txt'.
'''
'''
14) Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
'''
import pickle
11
def w():
with open("rec.dat", "ab") as f:
while True:
rn = int(input("ENTER ROLL NUMBER: "))
name = input("ENTER NAME: ")
def r():
try:
with open("rec.dat", "rb") as f:
data = []
while True:
try:
record = pickle.load(f)
data.append(record)
except EOFError:
break
if data:
print(data)
else:
print("No records found.")
except FileNotFoundError:
print("ERROR: File 'rec.dat' not found.")
def s():
try:
with open("rec.dat", "rb") as f:
data = []
while True:
try:
record = pickle.load(f)
data.append(record)
except EOFError:
break
12
if record[0] == trn:
print([record])
found = True
break
if not found:
print("RECORD NOT FOUND ERROR: RECORD DOESN'T EXIST")
except FileNotFoundError:
print("ERROR: File 'rec.dat' not found.")
w()
r()
s()
'''
Run code >>> py Tarun.py
O/P
ENTER ROLL NUMBER: 1
ENTER NAME: DORAEMON
DO YOU WANT TO ADD MORE RECORDS (Yes/No): yes
ENTER ROLL NUMBER: 2
ENTER NAME: NOBITA
DO YOU WANT TO ADD MORE RECORDS (Yes/No): no
[[1, 'DORAEMON'], [2, 'NOBITA']]
ENTER ROLL.NO TO DISPLAY SPECIFIC RECORD: 2
[[2, 'NOBITA']]
'''
'''
15) Create a CSV file by entering user_id and password, read and search the password for
given user_id.
'''
import csv
def create_csv_file():
user_data = [
{"user_id": "tarun703", "password": "GAMER2"},
{"user_id": "anuj123", "password": "GOALS3"},
{"user_id": "naina564", "password": "BEAUTY9"},
{"user_id": "sanidhya532", "password": "ICECREAM8"}
]
filename = 'users.csv'
file=open(filename, mode='w', newline='')
13
writer = csv.DictWriter(file, fieldnames=["user_id", "password"])
writer.writeheader()
writer.writerows(user_data)
# Function to read the CSV file and search for a password using user_id
def search_password(user_id):
filename = 'users.csv'
create_csv_file()
password = search_password(search_id)
if password:
print(f"The password for user_id '{search_id}' is: {password}")
else:
print(f"User ID '{search_id}' not found.")
'''
Run code >>> py Tarun.py
Enter user_id to search for password: tarun703
The password for user_id 'tarun703' is: GAMER2
14
Programs based on Python-SQL connectivity
'''
2) Retrieve data
3) Update Data
4) Delete Data
'''
#1) Connection and insert data
import mysql.connector
con = mysql.connector.connect(
host="localhost",
user="root",
password="Admin@123"
15
)
cur = con.cursor()
cur.execute('USE reportfile_db;')
cur.execute('
name VARCHAR(50),
class CHAR(2),
stream CHAR(3),
optional VARCHAR(20),
);
')
cur.execute(' insert into demo values (101, "ARMAN", "12", "PCM", "CS", "7896543577");')
cur.execute('insert into demo values (102, "MADHAV", "11", "PCB", "PHE", "9630258741");')
cur.execute(' insert into demo values (103, "SHRUTI", "11", "COMMERCE", "Painting",
"9889876546");')
cur.execute('insert into demo values (104, "UZAIR", "12", "PCM", "PHE", "8789876545");')
cur.execute('insert into demo values (105, "ANUJ", "12", "PCM", "CS", "9786668759");')
con.commit()
16
cur.execute(select * from demo;')
rec = cur.fetchall()
if rec == []:
else:
con.commit()
17
#4) Delete Data
con.commit()
18
19
20