0% found this document useful (0 votes)
12 views31 pages

Python Programming Exercises Guide

The document outlines a series of Python programming exercises, including tasks such as calculating factorials, generating Fibonacci series, checking for palindromes, and file manipulations. It also covers SQL commands and connectivity with MySQL, detailing how to create databases, tables, and perform CRUD operations. Each exercise is accompanied by example code and expected outputs.

Uploaded by

Yash Jangra
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)
12 views31 pages

Python Programming Exercises Guide

The document outlines a series of Python programming exercises, including tasks such as calculating factorials, generating Fibonacci series, checking for palindromes, and file manipulations. It also covers SQL commands and connectivity with MySQL, detailing how to create databases, tables, and perform CRUD operations. Each exercise is accompanied by example code and expected outputs.

Uploaded by

Yash Jangra
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

S.

No Remarks
Name of the Exercises
Python Programs
1. Write a program to find a factorial of a number
2. Creating a python program to display Fibonacci series
3. Write a program to find if a string is palindrome or not
4. Creating a python program to generate random number between 1 to 6
5. Write a program to find the sum of element of list
6. Write a program to remove all the lines that contain the character 'a' in a file and
write it to another file.
7. Creating a python program to read a text file and display the number of
vowels/consonants/lower case/ upper case characters.
8. Creating a python program to read a text file line by line and display each word
separated by '#'.
9. 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
10. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
11. Create a CSV file by entering user-id and password, read and search the password for
given user id
12. Creating a python program to implement stack operations (List)
13. Creating a python program to find exceptions
Python – SQL connectivity programs
14. Creating a python program to integrate MYSQL with Python

15. Creating a python program to integrate MYSQL with Python (Creating and display
database)
16. Creating a python program to integrate MYSQL with Python (Creating ,show and
display structure of table)
17. Creating a python program to integrate MYSQL with Python (Inserting records
and displaying records)
18. Creating a python program to integrate MYSQL with Python (Searching and
displaying records)
SQL Queries
19. SQL COMMANDS EXERCISE – 1
20. SQL COMMANDS EXERCISE – 2
21. SQL COMMANDS EXERCISE – 3
22. SQL COMMANDS EXERCISE – 4
23. SQL COMMANDS EXERCISE – 5
[Link] a program to find a factorial of a number

def factorial(a):
s=1
for i in range(a,0,-1):
s*=i
return s
x=int(input('enter the no.'))
fac=factorial(x)
print(The factorial of',x,'is ',fac)

OUTPUT
[Link] a program to find fibonacci series

def fibonacci(n):
ln=[]
a=0
b=1
for i in range(n):
c=a+b
a=b
b=c
[Link](a)
return ln
x=int(input('How any terms'))
print(fibonacci(x))

OUTPUT
[Link] a program to find if a string is palindrome or not

n1= input('Enter the string')


s=""
for i in range(1,len(n1)+1):
s+=n1[-i]
if s==n1:
print('It is a palindrome')
else:
print('It is not a palindrome')

OUTPUT
[Link] a program of random generator(simulates a dice)

import random
def roll_dice():
"""simulate rolling a dice"""
return [Link](1,6)
print("welcome to the dice roll simulator!")
print('please enter the times you want to roll the dice:')
try:
times=int(input("enter any number"))
if times<=0:
print("please enter a positive number")
else:
print("Rolling the dice....")
for _ in range(times):
print("You rolled a",roll_dice())
except Value Error:
print("invalid input. Please enter a number.")

OUTPUT
[Link] a program to find the sum of element of list

import pickle
emp={}
empfile= open('[Link]','rb')
emp=[Link]()
print(emp)
[Link]()

OUTPUT
6. Write a program to remove all the lines that contain the character 'a'
in a file and write it to another file.

#my original file contain data


'''this is duplicate FILE
FIL COPY
create file "class"
file is very beautiful #
every thing is #common in any thing
y text file, I mean any file for which the bits are intended to be
decoded using a standard text format,# such as ASCII or Unicode (e.g., 1100 1000 will
be “A” and so on). Also called “plain text” or “human readable”, these files are easy to
undertstand with any software that supports text or other documents.'''
f1 = open(r'C:\Users\dhpss\OneDrive\Desktop\[Link]')
f2 = open("[Link]","w")
for line in f1:
if 'a' not in line:
[Link](line)
print('## File Copied Successfully! ##')
[Link]()
[Link]()
f2 = open("[Link]","r")
print([Link]())
OUTPUT
7. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.

# function to count vowels and consonants in a string


f=open("[Link]","r")
str1=[Link]()
vcount=0
ccount=0
for i in str1:
if(i=='A' or i=='a' or i=='E' or i=='e' or i=='I' or i=='i' or i=='O' or i=='o' or i=='U' or
i=='u'):
vcount=vcount+1
else:ccount=ccount+1
print("vowels in thr file:",vcount)
print("consonants in the file:",ccount)
[Link]()

OUTPUT
8. Read a text file line by line and display each word separated by a #

#[Link] has following data


"""
welcome to python class
welcome to CBSE class 12 program 15
School programming
"""
fh=open(r"C:\Users\dhpss\OneDrive\Desktop\[Link]",'r')
item=[]
a=""
while True:
a=[Link]()
words=[Link]()
for j in words:
[Link](j)
if a =="":
break
print("#".join(item))

OUTPUT
9. 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

def create_file(name, roll_number):


with open('[Link]', 'ab') as file:
[Link]((name, roll_number), file)

def search_roll_number(roll_number):
with open('[Link]', 'rb') as file:
while True:
try:
name, number = [Link](file)
if number == roll_number:
return name
except EOFError:
break
return None

# Create some data


create_file('Ritika', 1)
create_file('Payal', 2)
create_file('Dev', 3)
create_file('Sweta', 4)
create_file('Rohit', 5)
create_file('Kapil', 6)

# Search for a roll number


rollno=int(input("Which students's roll number you wants to find"))
name = search_roll_number(rollno)
if name is not None:
print('Name: ', name)
else:
print('Roll number not found.')

OUTPUT
10. Create a binary file with roll number, name and marks. Input a roll
number and update the marks.

import pickle

def Write():
f= open("[Link]", 'wb')
while True:
r=int(input("Enter Roll no: "))
n = input("Enter Name: ")
m=int(input("Enter Marks: "))
record = [r,n,m]
[Link](record,f)
ch=input("Do you want to enter more ?(Y/N)")
if ch in 'Nn':
break
[Link]()

def Read():
f= open("[Link]", 'rb')
try:
while True:
rec=[Link](f)
print(rec)
except EOFError:
[Link]()

def Update():
f= open("[Link]", 'rb+')
rollno= int(input("Enter roll no whoes marks you want to update"))
try:
while True:
pos=[Link]()
rec = [Link](f)
if rec[0]==rollno:
um = int(input("Enter Update Marks: "))
rec[2]=um
[Link](pos)
[Link](rec,f)
#print(rec)
except EOFError:
[Link]()
Write()
Read()
Update()
Read()

OUTPUT
11. Create a CSV file by entering user-id and password, read and search
the password for given userid.

import csv

with open("[Link]", "w") as obj:


fileobj = [Link](obj)
[Link](["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
[Link](record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("[Link]", "r") as obj2:
fileobj2 = [Link](obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break
OUTPUT
12. Write a Python program to implement a stack using list.

stack = []
def push(element):
[Link](element)
print(element, " pushed to stack ")

def pop():
if not is_empty():
print([Link]()," popped from stack ")
else:
print("Stack is empty")

def is_empty():
return len(stack) == 0

def display():
if not is_empty():
print("Stack elements:")
for i in range(len(stack)-1, -1, -1):
print(stack[i])
else:
print("Stack is empty")

while True:
print("1. Push")
print("2. Pop")
print("3. Is Empty")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice: ")

if choice == '1':
element = input("Enter element to push: ")
push(element)
elif choice == '2':
pop()
elif choice == '3':
if is_empty():
print("Stack is empty")
else:
print("Stack is not empty")
elif choice == '4':
display()
elif choice == '5':
break
else:
print("Invalid choice")
OUTPUT
13. Write a Python program to perform exception handling.

def divide_numbers(a, b):


try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Division by Zero is not allowed")
except NameError:
print("Some name is not defined")
except Exception:
print("Some error occurred")

# Example usage
divide_numbers(10, 0) #This will raise a ZeroDivisionError
try:
divide_numbers(5, spam) # This will raise a NameError (assuming spam is not defined)
except NameError:
print("spam is not defined")
divide_numbers(8, 2) # This will execute successfully

OUTPUT
[Link] a python program to integrate MYSQL with Python

import [Link] as sqlcon


mydbs=[Link](host="localhost",user="root",passwd="123456")
if mydbs.is_connected():
print("successful connection")

OUTPUT

15. Creating a python program to integrate MYSQL with Python (Creating


database and display database)
import [Link] as sqlcon
mydbs=[Link](host="localhost",user="root",passwd="123456")
if mydbs.is_connected():
print("successful connection")

mycur=[Link]()
#create database
[Link]("create database dhps_school23")
#show database
[Link]("show databases")
for x in mycur:
print(x)

OUTPUT

[Link] a python program to integrate MYSQL with Python


(Creating ,show and display structure of table)
import [Link] as con
mydb=[Link](host="localhost",user="root",passwd="123456",database="dhps_sch
ool23")
mycur=[Link]()

#table creation
[Link]("create table student12(name varchar(20),rollno int(3),address
varchar(20))")
print("Table created successful")

print("-------------show table command--------------")


[Link]("show tables")
for x in mycur:
print(x)
print("-------------Display table structure-------------")
[Link]("desc student12")
for x in mycur:
print(x)

OUTPUT

[Link] a python program to integrate MYSQL with Python


(Inserting records and displaying records)

import [Link] as con


mydb=[Link](host="localhost",user="root",passwd="123456",database="dhps_sch
ool23")
mycur=[Link]()

query="insert into student12(name,rollno,address)values ('{}','{}','{}')".format


('Ankit',3,'Delhi')

[Link](query)
[Link]("select*from student12")
data1=[Link]()
count1=[Link]
print("total no. of row fetched=",count1)
for i in data1:
print(i)

print([Link],"inserted successfully")

[Link]()

OUTPUT

[Link] a python program to display records using fetch/


fetchmany(n) / fetchall method.
import [Link] as ctor
dbcon=[Link](host="localhost",user="root",passwd="123456",database="school")
cursor=[Link]()
[Link]("select * from smartstudent")

print("\t\tfetch one row data from table by useof fetchone command\n")


data=[Link]()
count1= [Link]
print("total no. of row fetched=",count1)
print(data)

print("\n \tfetch 3 records of table by use of fetch many\n")


data=[Link] many(3)
count=[Link]
for row in data:
print(row)
print("total no. of row fetched=",count)

print("\n\t\tfetch all data from table by use of fetchall command\n")


data1=[Link]()
count1= [Link]
print("total no. of row fetched=",count1)
for i in data1:
print(i)

OUTPUT
# CREATING DATABASES
Syntax : create database[if not exists]<database name
# SHOW DATABASE
Synatx : show databases;

# OPENING DATABASES
Syntax : use<databasename>;

# REMOVING DATABASES
Syntax : drop database<databasename>;

# CREATING TABLES
Synatx : create table<table name>(<column name><data type>[(size)],
<column name><data>[(size)]);

# INSERT COMMAND
Syntax : insert into<table Name>(column1, column2…)
Values(value1,value2,value3,……);

Syntax : insert into<table name>Values(value1,value2,value3,……);

# VIEW TABLE
Syntax : desc<tablename>;
# SELECT COMMAND
Syntax : Select * from (tablename);

Syntax : select<column1>,<column2>,…….from (table name):

Syntax : Select column(condition) from table name;


# UPDATE COMMAND
Synatx : update table_name SET column1=value1, column2=value2,………..
WHERE condition;

# ALTER COMMAND
Syntax : alter table<table name>add<column name><data type><size>[<constraint
name>];
# ALL KEYBOARDS
Syntax : select all<column name>FROM<table name>;

# WHERE CLAUSE
Syntax: select<column name>,[<column name><…] from <tablename> where
<condition> ;

# ORDER BY CLAUSE
Syntax : select*from<table name> order by<condition>;

# GROUP BY CLAUSE
Syntax : select count(<column name>), count(<column name>)from <table name>
group by <condition>;

# LIKE KEYBOARD
Syntax :select cloumn1, column2, ….from <table name> WHERE column LIKE
pattern;

# COUNT FUNCTION
Syntax : select count(*) “column_name”FROM<table name>;

# MAX FUNCTION
Syntax : select MAX(column_name) “column_name”FROM<tablename>;

You might also like