0% found this document useful (0 votes)
15 views20 pages

Taruncs 1

The document contains a series of Python programming exercises covering various topics such as random number generation, exception handling, file operations, data structures (like stacks), and searching algorithms. Each exercise includes code snippets, expected outputs, and explanations of the functionality. The exercises range from basic input/output operations to more complex tasks involving file manipulation and data storage.

Uploaded by

Tarun Mittal
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)
15 views20 pages

Taruncs 1

The document contains a series of Python programming exercises covering various topics such as random number generation, exception handling, file operations, data structures (like stacks), and searching algorithms. Each exercise includes code snippets, expected outputs, and explanations of the functionality. The exercises range from basic input/output operations to more complex tasks involving file manipulation and data storage.

Uploaded by

Tarun Mittal
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/ 20

'''

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: "))

record = {"item_no": item_no, "item_name": item_name, "qty": qty, "price": price}


pickle.dump(record, f)
print("Records added successfully!")

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

Item No: 102


Item Name: PENCIL BOX
Quantity: 15
Price/Item: 50.00
Amount: 750.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

THE LARGEST NUMBER IN IT IS- 31


'''

'''
6) Write a program to reverse a string using stack.
'''

def reverse_string(input_string):
stack = []

for char in input_string:

5
stack.append(char)

reversed_string = ""
while stack:
reversed_string += stack.pop()

return reversed_string

input_string = input("Enter a string to reverse: ")


reversed_string = reverse_string(input_string)

print(f"Reversed string: {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():

st=input("ENTER THE STUDENT NAME")

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']

THE ASCENDING ORDER OF YOUR GIVEN ITEMS ARE

[' Aayush', ' Devansh', ' Nikunj', ' Tarun']


'''

'''
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

numbers = [-10, 5, 3, -7, 8, -2, 11, -3, 6, 1]

keys = [3, 7, -11]

# Check each key


for key in keys:
position = linear_search(numbers, key)
if position != -1:
print(f"Key {key} found at position {position}.")
else:
print(f"Key {key} 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"

file = open(file_path, 'w')


l="HELLO EVERYONE,MY NAME IS TARUN,THIS IS MY C.S FILE"
file.writelines(l)
file.close()

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 = open(f_p, 'w')

l="Hello World!,Python is Fun."

file.writelines(l)

file.close()

try:
file = open(f_p, 'r')

vowels = 0
consonants = 0
uppercase = 0
lowercase = 0

vowels_set = set("aeiouAEIOU")

# Process each line in the file


for line in file:
for char in line:
if char.isalpha():
if char in vowels_set:
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
file.close()

print(f"Number of vowels: {vowels}")


print(f"Number of consonants: {consonants}")
print(f"Number of uppercase characters: {uppercase}")
print(f"Number of lowercase characters: {lowercase}")

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()

with open('input.txt', 'r') as infile :


for line in infile:
if 'a' not in line:
with open('output.txt', 'w') as outfile :
outfile.write(line)
print("\nlines containing 'a' have been removed and written to 'output.txt'.")
print()

'''
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: ")

data = [rn, name]


pickle.dump(data, f)

ch = input("DO YOU WANT TO ADD MORE RECORDS (Yes/No): ").strip().lower()


if ch == 'n' or ch == 'no':
break

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

trn = int(input("ENTER ROLL.NO TO DISPLAY SPECIFIC RECORD: "))


found = False
for record in data:

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)

print(f"CSV file '{filename}' created successfully.")

# Function to read the CSV file and search for a password using user_id
def search_password(user_id):
filename = 'users.csv'

file=open(filename, mode='r', newline='')


reader = csv.DictReader(file)

# Search through each row to find the user_id


for row in reader:
if row['user_id'] == user_id:
return row['password']

# Return None if user_id not found


return None

create_csv_file()

# Searching for a password for a specific user_id


search_id= input("Enter user_id to search for password: ")

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

Enter user_id to search for password: sanket434


User ID 'sanket434' not found.
'''

14
Programs based on Python-SQL connectivity

'''

List of Python programs that involve connecting to a MySQL database.

1) Connection and insert data

2) Retrieve data

3) Update Data

4) Delete Data

'''
#1) Connection and insert data

import mysql.connector

from tabulate import tabulate

con = mysql.connector.connect(

host="localhost",

user="root",

password="Admin@123"

15
)

cur = con.cursor()

cur.execute('create database if not exists reportfile_db;')

cur.execute('USE reportfile_db;')

cur.execute('

create table if not exists demo(

roll_no INT PRIMARY KEY,

name VARCHAR(50),

class CHAR(2),

stream CHAR(3),

optional VARCHAR(20),

phone_no CHAR(10) UNIQUE

);

')

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");')

cur.execute('insert into demo values (106, "TARUN", "12", "COMMERCE", "CS",


"9897640863");')

con.commit()

#2) Retrieve data

16
cur.execute(select * from demo;')

rec = cur.fetchall()

if rec == []:

print('No Record Found!')

else:

print(tabulate(rec, headers=['ROLL NO.', 'NAME', 'CLASS', 'STREAM', 'OPTIONAL',


'PHONE NO.']))

#3) Update Data

cur.execute('update demo set optional = "Painting" where roll_no = 105;')

con.commit()

17
#4) Delete Data

cur.execute('delete from demo where roll_no = 106;')

con.commit()

18
19
20

You might also like