• Click below to download Unit 4 programs in pdf file: -



Unit 4


# 1. Write a program to handle some built in exceptions like ZeroDivisionError.


try:

    a=(int)(input("enter the value of A :- "))

    b=(int)(input("enter the value of B :- "))

    x = a/b

    print("division of two value is ",x)

except ZeroDivisionError:

    print("You cant't divide ")



# 2. Write a program to handle multiple exceptions like SyntaxError and TypeError


try:

    #Demo Expression : 15*10-(10+2)

    expr=eval(input("enter Expression "))

    print("Expression is: ",expr)

    a=[1,2,3,4,5,6]

    b=[]

    c=a/b

    print(c)

except (TypeError,SyntaxError):

    print("syntax error or type error ")


""" 3. Write a program to import “os” module and to print the

current working directory and returns a list of all module

functions """

import os

print("current working directory:",os.getcwd())

print()


print("List of all os module function is:", dir(os))



""" 4. Write a program to provide a function for making file lists

from directory wildcard searches. """


import glob

path="C:\Desktop\BCA4GU\Sem 5\Syllabus Programs\Python\unit 4\\"

files=[f for f in glob.glob(path+"**/*.txt",recursive=True)]

 

for f in files:

    print(f)



""" 5. Write a program to import datetime module and format

the date as required. Also use the same module to

calculate the difference between your birthday and today

in days."""


from datetime import date

 

d1,m1,y1=[int(i) for i in input("enter date of birth in DD/MM/YY format:").split('/')]

dt=date(y1,m1,d1)

print("your birth date is:",dt.strftime("%d/%m/%y"))

 

d=date.today()

print("Todays is:",d.strftime("%d/%m/%y"))

 

year_d=d.strftime("%Y")

print("current year:"+year_d)

 

year_dt=dt.strftime("%Y")

print("birthday's year:"+year_dt)

print("Your Age is:",int(year_d)-int(year_dt))



""" 6. Write a program to create a database named

“Sample_DB” in MySQL(). [First ensure connection is

made or not and then check if the database Sample_DB

already exists or not, if yes then print appropriate

message] """


import mysql.connector as mydb

db_name=input("enter DatabaseName: ")

try:

    pydb=mydb.connect(host="localhost",user="root",passwd="")

except:

    print("there is a problem in connecting mysql")

else:

    try:

        pycursor=pydb.cursor()

        pycursor.execute("CREATE DATABASE %s"%db_name)

        pycursor.close()

    except:

        print("database %s already exists,please try to create database with othre name"%db_name)

    else:

        print("Databas %s sucessfully created"%db_name)



""" 7. Write a program to retrieve and display all the rows in

the employee table. [First create an employee table in the

Sample_DB with the fields as eid, name, sal . Also enter

some valid records] """


import mysql.connector as mydb

db_name=input("Enter DatabaseName:")

tb_name=input("Enter TableName:")

 

def create_table():

    pycursor=pydb.cursor()

    pycursor.execute("CREATE TABLE %s (eid int primary key,name varchar(20),salint)"%tb_name)

    print("Table %s is created successfully..."%tb_name)

    pycursor.close()

    insert_data()

 

def insert_data():

    n=int(input("Enter how many rows you want:"))

    for i in range(n):

        pycursor=pydb.cursor()

        eid1=int(input("Enter Employee id:"))

        name1=input("Enter Name")

        sal1=int(input("Enter Salary:"))

        pycursor.execute("insert into {0}(eid,name,sal) values({1},'{2}',{3})".format(tb_name,eid1,name1,sal1))

        pydb.commit()

        print(pycursor.rowcount,"Row Inserted Successfully")

        pycursor.close()

        select_data()

 

def select_data():

    pycursor=pydb.cursor()

    pycursor.execute("SELECT * FROM %s"%tb_name)

    res=pycursor.fetchall()

    if pycursor.rowcount>0:

        print(res,"\n")

    else:

    insert_data()

try:

    pydb=mydb.connect(host="localhost",user="root",passwd="",database=db_name)

except:

    print("Connection error.database name does not exists.")

else:

    try:

        create_table()

    except:

        print("Table %s already exists"%tb_name)

        select_data()

    else:

    print("Data inserted sucessfully")



""" 8. Write a program to insert several rows into employee table from the keyboard. """

import mysql.connector as mydb

db_name=input("Enter DatabaseName::->")

tb_name=input("Enter TableName::->")

 

def insert_data():

    try:

        n=int(input("Enter how many rows you want::"))

    for i in range(n):

        pycursor=pydb.cursor()

        eid1=int(input("Enter Employee id:->:"))

        name1=input("Enter Name::->")

        sal1=int(input("Enter Salary::->"))

        pycursor.execute("insert into {0}(eid,name,sal) values({1},'{2}',{3})".format(tb_name,eid1,name1,sal1))

        pydb.commit()

        print(pycursor.rowcount, "Row Inserted Successfully")

        pycursor.close()

    select_data()

except:

    print("table name does not exists.......")

else:

    print("Data sucessfully inserted.....")

 

def select_data():

    pycursor=pydb.cursor()

    pycursor.execute("SELECT * FROM %s"%tb_name)

    res=pycursor.fetchall()

    print(res,"\n")

    pycursor.close()

try:

    pydb=mydb.connect(host="localhost",user="root",passwd="",database=db_name)

except:

    print("Connection error.database name does not exists.")

else:

    try:

        insert_data()

    except:

        print("something went wrong,please try again")



""" 9. Write a program to delete a row from an employee table

by accepting the employee identity number (eid) from the

user. """


import mysql.connector as mydb

db_name=input("Enter DatabaseName:")

tb_name=input("Enter TableName:")

 

def delete_data():

    try:

        select_data()

        eid1=int(input("Enter Employee id:"))

        pycursor=pydb.cursor()

        pycursor.execute("Delete from {0} where eid={1}".format(tb_name,eid1))

        pydb.commit()

        print(pycursor.rowcount,"Row deleted Successfully")

        pycursor.close()

        select_data()

    except:

        print("table name does not exists")

    else:

        print("Data sucessfully deleted")

 

def select_data():

    pycursor=pydb.cursor()

    pycursor.execute("SELECT * FROM %s"%tb_name)

    res=pycursor.fetchall()

    print(res,"\n")

    pycursor.close()

try:

    pydb=mydb.connect(host="localhost",user="root",passwd="",database=db_name)

except:

    print("Connection error.database name does not exists.")

else:

    try:

      delete_data()

    except:

      print("something went wrong,please try again")



""" 10. Write a program to increase the salary (sal) of an

employee in the employee table by accepting the

employee identity number (eid) from the user. """


import mysql.connector as mydb

db_name=input("Enter DatabaseName:")

tb_name=input("Enter TableName:")

 

def update_data():

    try:

        select_data()

        eid1=int(input("Enter Employee id:"))

        pycursor=pydb.cursor()

        pycursor.execute("update {0} set sal=sal+(sal*5/100) where

        eid={1}".format(tb_name,eid1))

        pydb.commit()

        print(pycursor.rowcount,"Row updated Successfully")

        pycursor.close()

        select_data()

    except:

        print("table name does not exists")

    else:

        print("Data sucessfully updated")

def select_data():

    pycursor=pydb.cursor()

    pycursor.execute("SELECT * FROM %s"%tb_name)

    res=pycursor.fetchall()

    print(res,"\n")

    pycursor.close()

try:

    pydb=mydb.connect(host="localhost",user="root",passwd="",database=db_name)

except:

    print("Connection error.database name does not exists.")

else:

    try:

        update_data()

    except:

        print("something went wrong,please try again")



""" 11. Write a program to create a table named

new_employee_tbl with the fields eno , ename , gender

and salary in Sample_DB database. The datatypes of the

fields are eno-int, ename-char(30), gender-char(1) and

salary-float. """ 



import mysql.connector as mydb

db_name=input("Enter DatabaseName:")

tb_name=input("Enter TableName:")

 

def create_table():

    try:

        pycursor=pydb.cursor()

        pycursor.execute("CREATE TABLE %s(eno int(3), ename char(30),gender

        char(1),salary float(5))"%tb_name)

        pycursor.close()

    except:

        print("table name does not exists")

    else:

        print("table sucessfully created")

try:

    pydb=mydb.connect(host="localhost",user="root",passwd="",database=db_name)

except:

    print("Connection error.database name does not exists")

else:

    try:

        create_table()

    except:

        print("something went wrong,please try again")