0% found this document useful (0 votes)
74 views

CSA Lab Assessment

The document describes experiments conducted in Prolog as part of a course on Fundamentals of AI & ML Lab. Experiment 3 focuses on studying the "cut" and "fail" predicates in Prolog. It explains that the cut predicate (!) is used to eliminate choice points and avoid unnecessary backtracking during query evaluation. It removes all choice points created after the cut predicate. The fail predicate causes the goal to fail, thus avoiding further choice points. Examples are provided to demonstrate the usage of cut and fail.

Uploaded by

JOJO
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)
74 views

CSA Lab Assessment

The document describes experiments conducted in Prolog as part of a course on Fundamentals of AI & ML Lab. Experiment 3 focuses on studying the "cut" and "fail" predicates in Prolog. It explains that the cut predicate (!) is used to eliminate choice points and avoid unnecessary backtracking during query evaluation. It removes all choice points created after the cut predicate. The fail predicate causes the goal to fail, thus avoiding further choice points. Examples are provided to demonstrate the usage of cut and fail.

Uploaded by

JOJO
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/ 37

SCHOOL OF COMPUTING SCIENCE AND ENGINEERING

FALL SEMESTER: 2021-2022

CSA2001 – FUNDAMENTALS IN AI & ML LAB

FACULTY: Mr. E. Silambarasan (Emp. Id: 100343), APJ/SCSE

Submitted By
Reg No: 21BCE11055
Name: Akhand Pratap Tiwari

1
INDEX

Ex. No. EXPERIMENT NAME Pg. No. Marks

1 Study of facts, objects, predicates and variables in PROLOG. 3

2 Study of Rules and Unification in PROLOG. 5

3 Study of “cut” and “fail” predicate in PROLOG. 8

4 Study of arithmetic operators, simple input/output and compound 11


goals in PROLOG.
5 Study of recursion in PROLOG. – Factorial 13

6 Study of Lists in PROLOG. 14

7 Study of dynamic database in PROLOG. 15

8 Study of string operations in PROLOG. Implement string operations 17


like substring, string position, palindrome etc.)
9 Write a prolog program to maintain family tree. 19

10 Write a prolog program to implement all set operations (Union, 21


intersection, complement etc.)
11. Write a Python program to implement Library Management system. 23

2
Ex. No. 1 Study of facts, objects, predicates and variables in PROLOG.
Aim:

To study of facts, objects, predicates and variables in Prolog.

Description:

Symbols:
Prolog expressions are comprised of the following truth-functional symbols, which have the same
interpretation as in the predicate calculus.
English Predicate Calculus PROLOG
and ^ ,
or v ;
if --> :-
not ~ not

Variables and Names:


Variables begin with an uppercase letter. Predicate names, function names, and the names for
objects must begin with a lowercase letter. Rules for forming names are the same as for the
predicate calculus.
1- mother_of
2- male
3- female
4- greater_than
5- socrates

Facts:
A fact is a predicate expression that makes a declarative statement about the problem domain.
Whenever a variable occurs in a Prolog expression, it is assumed to be universally quantified. Note
that all Prolog sentences must end with a period.
likes(john, susie). /* John likes Susie */
likes(X, susie). /* Everyone likes Susie */
likes(john, Y). /* John likes everybody */
likes(john, Y), likes(Y, john). /* John likes everybody and everybody likes John */
likes(john, susie); likes(john,mary). /* John likes Susie or John likes Mary */
not(likes(john,pizza)). /* John does not like pizza */
likes(john,susie) :- likes(john,mary). /* John likes Susie if John likes Mary.

Queries:
The Prolog interpreter responds to queries about the facts and rules represented in its database.
The database is assumed to represent what is true about a particular problem domain. In making
a query you are asking Prolog whether it can prove that your query is true. If so, it answers "yes"
3
and displays any variable bindings that it made in coming up with the answer. If it fails to prove
the query true, it answers "No".
Whenever you run the Prolog interpreter, it will prompt you with ?-.

For example, suppose our database consists of the following facts about a fictitious family.
father_of(joe,paul).
father_of(joe,mary).
mother_of(jane,paul).
mother_of(jane,mary).
male(paul).
male(joe).
female(mary).
female(jane).

Program and Output:

Result:

Thus, the facts, objects, predicates and variables in Prolog were studied.

4
Ex. No. 2 Study of Rules and Unification in PROLOG.
Aim:

To Study of Rules and Unification in PROLOG.

Description:

Rules:
A rule is a predicate expression that uses logical implication (:-) to describe a relationship among
facts. Thus, a Prolog rule takes the form:

left_hand_side :- right_hand_side.

This sentence is interpreted as: left_hand_side if right_hand_side.


The left_hand_side is restricted to a single, positive, literal, which means it must consist of a
positive atomic expression. It cannot be negated and it cannot contain logical connectives.

This notation is known as a Horn clause. In Horn clause logic, the left-hand side of the clause is
the conclusion, and must be a single positive literal. The right-hand side contains the premises.
The Horn clause calculus is equivalent to the first-order predicate calculus.

Examples of valid rules:


friends(X,Y) :- likes(X,Y),likes(Y,X). /* X and Y are friends if they like each other */
hates(X,Y) :- not(likes(X,Y)). /* X hates Y if X does not like Y. */
enemies(X,Y) :- not(likes(X,Y)),not(likes(Y,X)). /* X and Y are enemies if they don't like each other
*/
Examples of invalid rules:
left_of(X,Y) :- right_of(Y,X) /* Missing a period */
likes(X,Y),likes(Y,X) :- friends(X,Y). /* LHS is not a single literal */
not(likes(X,Y)) :- hates(X,Y). /* LHS cannot be negated */

Unification:
Unification is a process of making two different logical atomic expressions identical by finding a
substitution. Unification depends on the substitution process.
It takes two literals as input and makes them identical using substitution.
Let Ψ1 and Ψ2 be two atomic sentences and 𝜎 be a unifier such that, Ψ1𝜎 = Ψ2𝜎, then it can be
expressed as UNIFY(Ψ1, Ψ2).

Example:
Find the MGU for Unify{King(x), King(John)}
Let Ψ1 = King(x), Ψ2 = King(John),
Substitution θ = {John/x} is a unifier for these atoms and applying this substitution, and both
expressions will be identical.
5
The UNIFY algorithm is used for unification, which takes two atomic sentences and returns a
unifier for those sentences (If any exist).
It returns fail if the expressions do not match with each other.
The substitution variables are called Most General Unifier or MGU.
E.g. Let's say there are two different expressions, P(x, y), and P(a, f(z)).
In this example, we need to make both above statements identical to each other. For this, we will
perform the substitution.
P(x, y)----------(i)
P(a, f(z))-------(ii)
Substitute x with a, and y with f(z) in the first expression, and it will be represented as a/x and
f(z)/y.
With both the substitutions, the first expression will be identical to the second expression and the
substitution set will be: [a/x, f(z)/y]

Conditions for Unification:


1- Predicate symbol must be same, atoms or expression with different predicate symbol can
never be unified.
2- Number of Arguments in both expressions must be identical.
3- Unification will fail if there are two similar variables present in the same expression.

Algorithm:
Unify(Ψ1, Ψ2)
Step. 1: If Ψ1 or Ψ2 is a variable or constant, then:
a) If Ψ1 or Ψ2 are identical, then return NIL.
b) Else if Ψ1is a variable,
a. then if Ψ1 occurs in Ψ2, then return FAILURE
b. Else return {(Ψ2/ Ψ1)}.
c) Else if Ψ2 is a variable,
a. If Ψ2 occurs in Ψ1 then return FAILURE,
b. Else return {( Ψ1/ Ψ2)}.
d) Else return FAILURE.
Step.2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return FAILURE.
Step.3: IF Ψ1 and Ψ2 have a different number of arguments, then return FAILURE.
Step.4: Set Substitution set(SUBST) to NIL.
Step.5: For i=1 to the number of elements in Ψ1.
a) Call Unify function with the ith element of Ψ1 and ith element of Ψ2, and put the result into S.
b) If S = failure then returns Failure
c) If S ≠ NIL then do,
a. Apply S to the remainder of both L1 and L2.
b. SUBST= APPEND(S, SUBST).
Step.6: Return SUBST.

Examples:
Find the MGU of {p (X, X), and p (Z, f(Z))}
Here, Ψ1 = {p (X, X), and Ψ2 = p (Z, f(Z))
S0 => {p (X, X), p (Z, f(Z))}
6
SUBST θ= {X/Z}
              S1 => {p (Z, Z), p (Z, f(Z))}
SUBST θ= {f(Z) / Z}
Unification Failed
Hence, unification is not possible for these expressions.
Find the MGU of UNIFY(prime (11), prime(y))
Here, Ψ1 = {prime(11) , and Ψ2 = prime(y)}
S0 => {prime(11) , prime(y)}
SUBST θ= {11/y}
S1 => {prime(11) , prime(11)} ,
Successfully unified.
Unifier: {11/y}.

Program and Output:

7
Result:

Hence, Rules and Unification were studied.

Ex. No. 3 Study of “cut” and “fail” predicate in PROLOG.


Aim:

To study cut and fail predicates in RPOLOG.

Description:

Cut:
Sometimes we write the same predicates more than once when our program demands, for
example to write recursive rules or to make some decision-making systems.
In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we
will use the Cut in Prolog.

Example:
Suppose we have some rules as follows:
Double step function:
Rule 1: if X < 3 then Y = 0
Rule 2: if 3 <= X and X < 6 then Y = 2
Rule 3: if 6 <= X then Y = 4
In Prolog syntax we can write:
f(X,0) :- X < 3. % Rule 1
f(X,2) :- 3 =< X, X < 6. % Rule 2
8
f(X,4) :- 6 =< X. % Rule 3

Now if we ask for a question as f (1,Y), 2 < Y.


The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries
through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can
observe that:
1- The three rules are mutually exclusive and one of them at most will succeed.
2- As soon as one of them succeeds there is no point in trying to use the others as they are bound
to fail.
So, we can use cut to resolve this. The cut can be expressed using Exclamation symbol.
The prolog syntax is as follows:
f (X,0) :- X < 3, !. % Rule 1
f (X,2) :- 3 =< X, X < 6, !. % Rule 2
f (X,4) :- 6 =< X. % Rule 3

Now if we use the same question:


?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to
backtrack, but not beyond the point marked!
In the program, rule 2 and rule 3 will not be generated.

Fail:
Here we will perform failure when condition does not satisfy. Suppose we have a statement, “Mary
likes all animals but snakes”, we will express this in Prolog. It would be very easy and straight
forward, if the statement is “Mary likes all animals”. In that case we can write “Mary likes X if X is
an animal”. And in prolog we can write this statement as, likes(mary, X) :-- animal(X).

Example:
Our actual statement can be expressed as:
If X is snake, then “Mary likes X” is not true
Otherwise, if X is an animal, then Mary likes X.

In prolog we can write this as:


likes(mary,X) :- snake(X), !, fail.
likes(mary, X) :- animal(X).
The ‘fail’ statement causes the failure.

Program and Output:

9
Result:

Hence, “cut” and “fail” predicate in PROLOG were studied.

10
Ex. No. 4 Study of arithmetic operators, simple input/output and
compound goals in PROLOG.
Aim:

To study arithmetic operators, simple input/output and compound goals in PROLOG.

Description:

Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations. There are few different types of
arithmetic operators as follows:
Symbols:

Example:
calc :- X is 100 + 200,write('100 + 200 is '),write(X),nl,
Y is 400 - 150,write('400 - 150 is '),write(Y),nl,
Z is 10 * 300,write('10 * 300 is '),write(Z),nl,
A is 100 / 30,write('100 / 30 is '),write(A),nl,
B is 100 // 30,write('100 // 30 is '),write(B),nl,
C is 100 ** 2,write('100 ** 2 is '),write(C),nl,
D is 100 mod 30,write('100 mod 30 is '),write(D),nl.

Simple I/O:

1- The write() Predicate:


To write the output we can use the write() predicate. This predicate takes the parameter as input,
and writes the content into the console by default. write() can also write in files. The write()
predicate can write the contents into the console. We can use ’nl’ to create a new line. If we want
to print some string on the console, we have to use single quotes (‘string‘). But if we use double
quote (“string”), then it will return a list of ASCII values.

2- The read() Predicate:


The read() predicate is used to read from console. User can write something in the console, that
11
can be taken as input and process it. The read() is generally used to read from console, but this can
also be used to read from files.

3- The tab() Predicate:


The tab() is one additional predicate that can be used to put some blank-spaces while we write
something. So it takes a number as an argument, and prints those many number of blank spaces.

Example:
add(Z, X, Y) :- read(X), read(Y), Z is X + Y, tab(5), write(Z).

Compound Goals:
Simple goals can be combined to form compound Goals. For example, we might want to know if
there is anything good to eat in the kitchen. In Prolog we might ask:

?- location(X, kitchen), edible(X).

Whereas a simple query had a single goal, the compound query has a conjunction of goals. The
comma separating the goals is read as "and."
Logically (declaratively) the example means "Is there an X such that X is located in the kitchen and
X is edible?" If the same variable name appears more than once in a query, it must have the same
value in all places it appears. The query in the above example will only succeed if there is a single
value of X that can satisfy both goals.
However, the variable name has no significance to any other query, or clause in the database. If X
appears in other queries or clauses, that query or clause gets its own copy of the variable. We say
the scope of a logical variable is a query.

Example:
Trying the sample query we get
?- location(X, kitchen), edible(X).
X = apple ;
X = crackers ;
Yes

If the user types semicolon (;) after an answer, the query is re-entered at the redo port of the
rightmost goal. Only the variable bindings that were set in that goal are undone.
If the query finishes via the fail port of the leftmost goal, the query fails.

Program and Output:

12
Result:

Hence, arithmetic operators, simple input/output and compound goals in PROLOG were studied.

Ex. No. 5 Study of recursion in PROLOG. – Factorial


Aim:

To study recursion in PROLOG and use Factorial as example.

Description:

Recursion is a technique in which one predicate uses itself (may be with some other
predicates) to find the truth value.
Example:
is_digesting(X, Y) :- just_ate(X,Y).
is_digesting(X, Y) :-just_ate(X,Z),is_digesting(Z,Y).

Program and Output:

13
Result:

Hence, recursion in PROLOG was studied using Factorial as example

Ex. No. 6 Study of Lists in PROLOG.


Aim:

To study lists in Prolog.

Description:

The list is a simple data structure that is widely used in non-numeric programming. List consists
of any number of items, for example, red, green, blue, white, dark. It will be represented as, [red,
green, blue, white, dark]. The list of elements will be enclosed with square brackets. A list can be
either empty or non-empty. The first item, called the head of the list. The remaining part of the list,
called the tail.

Operations one can perform on list:


Membership Checking - During this operation, we can verify whether a given element is member
of specified list or not?
Length - With this operation, we can find the length of a list.
Concatenation - Concatenation is an operation which is used to join/add two lists.
Deletion - This operation removes the specified element from a list.
Append - Append operation adds one list into another (as an item).
14
Insertion - This operation inserts a given item into a list.
Permutation - This operation will change the list item positions and generate all possible
outcomes.
Reverse Items - This operation arranges the items of a list in reverse order.
Shift Items - This operation will shift one element of a list to the left rotationally.
Order Items - This operation verifies whether the given list is ordered or not.

Example:
Membership Checking program given below:

Program and Output:

Result:

Hence, Lists were studied.

Ex. No. 7 Study of dynamic database in PROLOG.


Aim:

To study dynamic database in PROLOG.

Description:

Dynamic database can change dynamically at execution time and are of two types: -

Type1: created at each execution. It grows, shrinks and is deleted at the end of program. This
15
type of database is no longer available after program finishes its execution and is called working
memory.
Type2: Other type of dynamic databases are those which are stored in files and called database
files.
1- These are consulted in any program whenever required.
2- These types of databases are not part of any particular program and are available for use in
future by different programs using system defined predicates called save and consult.
3- While executing a Prolog program one can load database file(s) using 'consult' predicate.
4- These files can be updated dynamically at run time and saved using 'save' predicate.
The format of predicates 'save' and 'consult' are as follows:
1- save(filename) - succeeds after saving the contents of a file named 'filename’.
2- consult(filename) - succeeds after loading or adding all the clauses from a file stored in
'filename' in the current program being executed.
3- reconsult(filename) - succeeds after loading all the clauses by superseding all the existing
clauses for the same predicate from a file 'filename’.
● Grouping of rules and facts into partitions can be easily.

● Example: Load a file named 'more' if predicates P and Q succeed,


R: - P, Q, consult('more').
Clauses can be added to a database at run time using following predicates:
asserta(X) & assertz(X) - succeed by adding fact X in the beginning & at the end of database of
facts respectively.

● For example, asserta(father(mike, john)) adds fact father(mike, john) in the beginning of
current database.
● Clauses can be constructed dynamically and asserted in a dynamic database as follows:
start: -writeln ('Input name of mother: '),
readln(M), writeln('Input name of child: '),
readln(C), assert (parent (M, C)), assert(female(M)).
Similarly obsolete clauses can be deleted by using system defined predicate called retract from
dynamic database at the run time.
● For example, retract (father (mike, X)) deletes the first fact father (mike, _) from working
memory.
● retractall(X) deletes all clauses from a database whose head match with X.
● Example, retractall(father(X, Y)) deletes all the facts father( _ , _ ) and retractall( _ ) deletes
all the clauses from the working memory.

Program and Output:

Fibonacci series program:

16
Result:

Hence, Dynamic databases were studied.

Ex. No. 8 Study of string operations in PROLOG. Implement string


operations like substring, string position, palindrome etc.)
Aim:

To study and implement following string operations:


1- Sub-String Division.
2- Palindrome.
3- Uppercase to Lowercase conversion.
4- Lowercase to Uppercase conversion.

Description:

1- In Substring we slice a given string into a substring from a given position.


2- In conversion from upper to lower case we convert the input characters to lowercase.
3- In conversion from lower to upper case we convert the input characters to uppercase.
4- In palindrome we check whether the string looks same after we reverse the order of
characters in string.

1- sub_string(+String, ?Before, ?Length, ?After, ?SubString):


This predicate is functionally equivalent to sub_atom/5, but operates on strings. Note that this
implies the string input arguments can be either strings or atoms. If SubString is unbound

17
(output) it is unified with a string. The following example splits a string of the form
<name>=<value> into the name part (an atom) and the value (a string).
name_value(String, Name, Value) :-
sub_string(String, Before, _, After, "="),!,
sub_atom(String, 0, Before, _, Name),
sub_string(String, _, After, 0, Value).

2- string_upper(+String, -UpperCase):
Convert String to upper case and unify the result with UpperCase. This predicate is inbuilt.

3- string_lower(+String, LowerCase):
Convert String to lower case and unify the result with LowerCase. This predicate is inbuilt.

Examples:
Below program illustrates the above concepts with code:

Program and Output:

18
Result:

Thus, String operations were studied.

Ex. No. 9 Make a family tree program in PROLOG


Aim:

To make a program in prolog to maintain a family tree.

19
Description:

In Prolog programs, we specify relationships between objects and properties of the objects. Here
we will see the family relationship. There are various kinds of relationships, of which some can
be rules as well. A rule can find out about a relationship even if the relationship is not defined
explicitly as a fact.
We can define a brother relationship as follows:

Example:

Two persons are brothers, if,


1- They both are male.
2- They have the same parent.

Now consider we have the below phrases:


parent(sudip, piyush).
parent(sudip, raj).
male(piyush).
male(raj).
brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)

These clauses can give us the answer that piyush and raj are brothers, but we will get three
pairs of output here. They are: (piyush, piyush), (piyush, raj), (raj, raj). For these pairs, given
conditions are true, but for the pairs (piyush, piyush), (raj, raj), they are not actually
brothers, they are the same persons. So, we have to create the clauses properly to form a
relationship.

The revised relationship can be as follows:


A and B are brothers if:
1- A and B, both are male
2- They have same father
3- They have same mother
4- A and B are not same

This is an example of complex relationship that can be formed using Prolog. We want to make a
family tree, and that will be mapped into facts and rules, then we can run some queries on them.

Suppose the family tree is as follows:

20
The code, knowledge base, facts and relationships are illustrated below in the program:

Program and Output:

Result:

21
Thus, we made a program to maintain a family tree.

Ex. No. 10 Make a program to implement all the set operations in


PROLOG
Aim:

To make a program that shows all the set operations.

Description:

We are going to perform set operations using the list. Following are the set operations:

Subset Finding Operation:


We will try to write a clause that will get all possible subsets of a given set. So if the set is [a,b],
then the result will be [], [a], [b], [a,b]. To do so, we will create one clause, list_subset(L, X). It will
take L and return each subset into X. So, we will proceed in the following way:
1- If list is empty, the subset is also empty.
2- Find the subset recursively by retaining the Head, and
3- Make another recursive call where we will remove Head.

Union Operation:
We will define a clause called list_union(L1, L2, L3). So, this will take L1 and L2, and perform
Union on them, and store the result into L3. As you know if two lists have the same element
twice, then after union, there will be only one. So, we need another helper clause to check
the membership.

Intersection Operation:
We will define a clause called list_intersection(L1, L2, L3). So, this will take L1 and L2, and
perform Intersection operation, and store the result into L3. Intersection will return those
elements that are present in both lists. So L1 = [a, b, c, d, e], L2 = [a, e, i, o, u], then L3 =
[a, e]. Here, we will use the list_member() clause to check if one element is present in a
list or not.

Program and Output:

22
Result:

Thus, Set operations were successfully demonstrated.

Ex. No. 11 Make a Python program to make Library Management System


Aim:

To make a library management system in Python.

Description:

To make a library management system we need to keep following points in mind:


1- Total Number of books and change in them as one borrows or returns them.
2- Fine System on damage or late return.
3- Unique number system for keeping record of every book.
4- For this we have to implement following features:
Add Books: With this feature we can add Books in LMS system with book details like
Title,Author, Publisher, Price, Number of books...
Add Member: With this Add Member feature we can add Member details Member
Name, Mobile Number, Email Address, Class Name and address of the Member
Update Book : Update the previous entered Book details
Update Member : Update the Member details
Issue Book: This will record the details on the Book issued to whom. This Feature
23
stores the details of Book ID, Member ID , Issue Date, Return Date and Fine if anything is
pending from the student/member
Return Book : Update the Book Transactions on returned by the member
Search Menu: Search The Books which are available in the System
Report Menu: Return the Reports based on Books, Publisher, Member search

This LMS project store the data in database, this Project created a MySQL database with
name "library"
This Database has 3 tables to store and retrieve the data about the LMS system.
To implement python Library Management project used below modules
MySql Connector : This module is used to connect mysql database to fetch/add data
into database
DateTime : To set date and get current date and update the details on the tables

For these things we need to make a database for the books and use SQL in the backend in
conjunction with Python to keep the records and all the info about the books and to update it
also if needed.
To keep things simple in frontend we are going to use simple console rather than a distinct GUI.

Program and Output:

Code:
#   project name    : Library management system
#   made by         : RRTutors

import mysql.connector
from datetime import date

fine_per_day =5.0  #global variable

def clear():
  for _ in range(1):
     print

def add_book():
  conn = mysql.connector.connect(
       host='localhost', database='library', user='root', password='')
  cursor = conn.cursor()

  title = input('Enter Book Title :')


  author = input('Enter Book Author : ')
  publisher = input('Enter Book Publisher : ')
  pages = input('Enter Book Pages : ')
  price = input('Enter Book Price : ')

24
  edition = input('Enter Book Edition : ')
  copies  = int(input('Enter copies : '))
  sql = 'insert into book(title,author,price,pages,publisher,edition,status) values ( "' + \
       title + '","' + author+'",'+price+','+pages+',"'+publisher+'","'+edition+'","available");'
   #sql2 = 'insert into transaction(dot,qty,type) values ("'+str(today)+'",'+qty+',"purchase");'
  #print(sql)
  for _ in range(0,copies):
    cursor.execute(sql)
  conn.close()
  print('\n\nNew Book added successfully')
  wait = input('\n\n\n Press any key to continue....')

def add_member():
  conn = mysql.connector.connect(
      host='localhost', database='library', user='root', password='')
  cursor = conn.cursor()

  name = input('Enter Member Name :')


  clas = input('Enter Member Class & Section : ')
  address = input('Enter Member Address : ')
  phone = input('Enter Member Phone  : ')
  email = input('Enter Member Email  : ')
 
 
  sql = 'insert into member(name,class,address,phone,email) values ( "' + \
      name + '","' + clas+'","'+address+'","'+phone + \
        '","'+email+'");'
  #sql2 = 'insert into transaction(dot,qty,type) values ("'+str(today)+'",'+qty+',"purchase");'
  #print(sql)
 
  cursor.execute(sql)
  conn.close()
  print('\n\nNew Member added successfully')
  wait = input('\n\n\n Press any key to continue....')

def modify_book():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    clear()
    print('Modify BOOK Details Screen ')
    print('-'*120)
    print('\n1. Book Title')
    print('\n2. Book Author')
25
    print('\n3. Book Publisher')
    print('\n4. Book Pages')
    print('\n5. Book Price')
    print('\n6. Book Edition')
    print('\n\n')
    choice = int(input('Enter your choice :'))
    field = ''
    if choice == 1:
        field = 'title'
    if choice == 2:
        field = 'author'
    if choice == 3:
        field = 'publisher'
    if choice == 4:
        field = 'pages'
    if choice == 5:
        field = 'price'
    book_id = input('Enter Book ID :')
    value = input('Enter new value :')
    if field =='pages' or field == 'price':
        sql = 'update book set ' + field + ' = '+value+' where id = '+book_id+';'
    else:
        sql = 'update book set ' + field + ' = "'+value+'" where id = '+book_id+';'
    #print(sql)
    cursor.execute(sql)
    print('\n\n\nBook details Updated.....')
    conn.close()
    wait = input('\n\n\n Press any key to continue....')

def modify_member():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    clear()
    print('Modify Memeber Information Screen ')
    print('-'*120)
    print('\n1. Name')
    print('\n2. Class')
    print('\n3. address')
    print('\n4. Phone')
    print('\n5. Emaile')
    print('\n\n')
    choice = int(input('Enter your choice :'))
    field =''
    if choice == 1:
26
        field ='name'
    if choice == 2:
        field = 'class'
    if choice ==3:
        field ='address'
    if choice == 4:
        field = 'phone'
    if choice == 5:
        field = 'email'
    mem_id =input('Enter member ID :')
    value = input('Enter new value :')
    sql = 'update member set '+ field +' = "'+value+'" where id = '+mem_id+';'
    #print(sql)
    cursor.execute(sql)
    print('Member details Updated.....')
    conn.close()
    wait = input('\n\n\n Press any key to continue....')

def mem_issue_status(mem_id):
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    sql ='select * from transaction where m_id ='+mem_id +' and dor is NULL;'
    #print(sql)
    cursor.execute(sql)
    results = cursor.fetchall()
    return results

def book_status(book_id):
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    sql = 'select * from book where id ='+book_id + ';'
    cursor.execute(sql)
    result = cursor.fetchone()
    return result[5]

def book_issue_status(book_id,mem_id):
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    sql = 'select * from transaction where b_id ='+book_id + ' and m_id ='+ mem_id +' and dor is NULL;'
    cursor.execute(sql)
    result = cursor.fetchone()
27
    return result

def issue_book():
    conn = mysql.connector.connect(
      host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n BOOK ISSUE SCREEN ')
    print('-'*120)
    book_id = input('Enter Book  ID : ')
    mem_id  = input('Enter Member ID :')
  
  
    result = book_status(book_id)
    result1 = mem_issue_status(mem_id)
    #print(result1)
    today = date.today()
    if len(result1) == 0:
      if result == 'available':
          sql = 'insert into transaction(b_id, m_id, doi) values('+book_id+','+mem_id+',"'+str(today)+'");'
          sql_book = 'update book set status="issue" where id ='+book_id + ';'
          cursor.execute(sql)
          cursor.execute(sql_book)
          print('\n\n\n Book issued successfully')
      else:
          print('\n\nBook is not available for ISSUE... Current status :',result1)
    else:
      if len(result1)<1:
        sql = 'insert into transaction(b_id, m_id, doi) values(' + \
             book_id+','+mem_id+',"'+str(today)+'");'
        sql_book = 'update book set status="issue" where id ='+book_id + ';'
        #print(len(result))
        cursor.execute(sql)
        cursor.execute(sql_book)
        print('\n\n\n Book issued successfully')
      else:
        print('\n\nMember already have book from the Library')
      #print(result)

    conn.close()
    wait = input('\n\n\n Press any key to continue....')

def return_book():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
28
    cursor = conn.cursor()
    global fine_per_day
    clear()
    print('\n BOOK RETURN SCREEN ')
    print('-'*120)
    book_id = input('Enter Book  ID : ')
    mem_id = input('Enter Member ID :')
    today =date.today()
    result = book_issue_status(book_id,mem_id)
    if result==None:
       print('Book was not issued...Check Book Id and Member ID again..')
    else:
       sql='update book set status ="available" where id ='+book_id +';'
       din = (today - result[3]).days
       fine = din * fine_per_day    #  fine per data
       sql1 = 'update transaction set dor ="'+str(today)+'" , fine='+str(fine)+' where b_id='+book_id +' and
m_id='+mem_id+' and dor is NULL;'
    
       cursor.execute(sql)
       cursor.execute(sql1)
       print('\n\nBook returned successfully')
    conn.close()
    wait = input('\n\n\n Press any key to continue....')

def search_book(field):
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n BOOK SEARCH SCREEN ')
    print('-'*120)
    msg ='Enter '+ field +' Value :'
    title = input(msg)
    sql ='select * from book where '+ field + ' like "%'+ title+'%"'
    cursor.execute(sql)
    records = cursor.fetchall()
    clear()
    print('Search Result for :',field,' :' ,title)
    print('-'*120)
    for record in records:
      print(record)
    conn.close()
    wait = input('\n\n\n Press any key to continue....')

def search_menu():
29
    while True:
      clear()
      print(' S E A R C H   M E N U ')
      print("\n1.  Book Title")
      print('\n2.  Book Author')
      print('\n3.  Publisher')
      print('\n4.  Exit to main Menu')
      print('\n\n')
      choice = int(input('Enter your choice ...: '))
      field =''
      if choice == 1:
        field='title'
      if choice == 2:
        field = 'author'
      if choice == 3:
        field = 'publisher'
      if choice == 4:
        break
      search_book(field)

def reprot_book_list():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n REPORT - BOOK TITLES ')
    print('-'*120)
    sql ='select * from book'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_issued_books():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n REPORT - BOOK TITLES - Issued')
    print('-'*120)
30
    sql = 'select * from book where status = "issue";'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_available_books():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n REPORT - BOOK TITLES - Available')
    print('-'*120)
    sql = 'select * from book where status = "available";'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_weed_out_books():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n REPORT - BOOK TITLES - Weed Out')
    print('-'*120)
    sql = 'select * from book where status = "weed-out";'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_stolen_books():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
31
    cursor = conn.cursor()

    clear()
    print('\n REPORT - BOOK TITLES - Stolen')
    print('-'*120)
    sql = 'select * from book where status = "stolen";'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_lost_books():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n REPORT - BOOK TITLES - lost')
    print('-'*120)
    sql = 'select * from book where status = "lost";'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_member_list():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()

    clear()
    print('\n REPORT - Members List ')
    print('-'*120)
    sql = 'select * from member'
    cursor.execute(sql)
    records = cursor.fetchall()
    for record in records:
       print(record)
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')
32
def report_fine_collection():
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    sql ='select sum(fine) from transaction where dor ="'+str(date.today())+'";'
    cursor.execute(sql)
    result = cursor.fetchone() #always return values in the form of tuple
    clear()
    print('Fine collection')
    print('-'*120)
    print('Total fine collected Today :',result[0])
    print('\n\n\n')
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def report_menu():
    while True:
      clear()
      print(' R E P O R T    M E N U ')
      print("\n1.  Book List")
      print('\n2.  Member List')
      print('\n3.  Issued Books')
      print('\n4.  Available Books')
      print('\n5.  Weed out Book')
      print('\n6.  Stolen Book')
      print('\n7.  Lost Book')
      print('\n8.  Fine Collection')
      print('\n9.  Exit to main Menu')
      print('\n\n')
      choice = int(input('Enter your choice ...: '))

      if choice == 1:
        reprot_book_list()
      if choice == 2:
        report_member_list()
      if choice == 3:
        report_issued_books()
      if choice == 4:
        report_available_books()
      if choice == 5:
        report_weed_out_books()
      if choice == 6:
        report_stolen_books()
33
      if choice == 7:
        report_lost_books()
      if choice == 8:
        report_fine_collection()
      if choice == 9:
        break

def change_book_status(status,book_id):
    conn = mysql.connector.connect(
        host='localhost', database='library', user='root', password='')
    cursor = conn.cursor()
    sql = 'update book set status = "'+status +'" where id ='+book_id + ' and status ="available"'
    cursor.execute(sql)
    print('Book status changed to ',status)
    print('\n\n\n')
    conn.close()
    wait = input('\n\n\nPress any key to continue.....')

def special_menu():

    while True:
      clear()
      print(' S P E C I A L     M E N U')
      print("\n1.  Book Stolen")
      print('\n2.  Book Lost')
      print('\n3.  Book Weed out')
      print('\n4.  Return Book')
      print('\n\n')
      choice = int(input('Enter your choice ...: '))
      status=''
      if choice == 1:
         status ='stolen'
      if choice == 2:
         status = 'lost'
      if choice == 3:
         status = 'weed-out'
      if choice == 4:
         break
      book_id = input('Enter book id :')
      change_book_status(status,book_id)

def main_menu():
    while True:
      clear()
34
      print(' L I B R A R Y    M E N U')
      print("\n1.  Add Books")
      print('\n2.  Add Member')
      print('\n3.  Modify Book Information')
      print('\n4.  Modify Student Information')
      print('\n5.  Issue Book')
      print('\n6.  Return Book')
      print('\n7.  Search Menu')
      print('\n8.  Report Menu')
      print('\n9.  Special Menu')
      print('\n0.  Close application')
      print('\n\n')
      choice = int(input('Enter your choice ...: '))

      if choice == 1:
        add_book()
      if choice == 2:
        add_member()
      if choice == 3:
        modify_book()
      if choice == 4:
        modify_member()
      if choice == 5:
        issue_book()
      if choice == 6:
        return_book()
      if choice == 7:
        search_menu()
      if choice == 8:
        report_menu()
      if choice == 9:
        special_menu()
      if choice == 0:
        break

if __name__ == "__main__":
    main_menu()

Output:

35
36
Result:

Hence, we made a library management program that connects to a given database and works
with it.

37

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy