python for ai
python for ai
History
Ancient Times
Modern Founders of AI
Achievements of AI
Deep Thought is an international grand master chess player.
Sphinx can recognise continuous speech without training for each speaker. It
operates in near real time using a vocabulary of 1000 words and has 94% word
accuracy.
Navlab is a truck that can drive along a road at 55mph in normal traffic.
Carlton and United Breweries use an AI planning system to plan production of
their beer.
Robots are used regularly in manufacturing.
Natural language interfaces to databases can be obtained on a PC.
Machine Learning methods have been used to build expert systems.
Expert systems are used regularly in finance, medicine, manufacturing, and
agriculture
Symbolic Representations
To construct intelligent systems it is necessary to employ internal representations of a
symbolic nature, with cognitive activity corresponding to computational manipulation
of these symbolic representations. The symbolic representations must refer to the
external world.
Non-symbolic Representations
Knowledge is represented by weights on connections in a network
• >>>
• >>> print("Python is fun!")
• Python is fun!
• That’s it! You’ve just written your first Python program! When you’re done,
you can use exit() or quit() to leave the interactive session, or you can use
the following key combinations:
• macOS and Linux: Ctrl+D
• Windows: Ctrl+D and then press Enter
The Basic Python Syntax
• The Python syntax is clear, concise, and focused on readability. Readability
is arguably one of the more attractive features of the language itself. It
makes Python ideal for people who are learning to program. There are
several important components of the Python syntax:
• Comments
• Variables
• Keywords
• Built-in data types
• Conditional statements
• Loops
• Functions
Comments
• Comments are pieces of text that live in your code but are ignored by the Python
interpreter as it executes the code. You can use comments to describe the code so
that you and other developers can quickly understand what the code does or why
the code is written in a given way. To write a comment in Python, just add a hash
mark (#) before your comment text:
• # This is a comment on its own line
• The Python interpreter ignores the text after the hash mark and up to the end of
the line. You can also add inline comments to your code. In other words, you can
combine a Python expression or statement with a comment in a single line, given
that the comment occupies the final part of the line:
• var = "Hello, World!" # This is an inline comment
• You should use inline comments sparingly to clear up pieces of code that aren’t
obvious on their own. In general, your comments should be short and to the point.
Variables
• In Python, variables are names attached to a particular object. They hold a reference,
or pointer, to the memory address at which an object is stored. Once a variable is assigned
an object, you can access the object using the variable name.
• You need to define your variables in advance. Here’s the syntax:
• variable_name = variable_value
• You should use a naming scheme that makes your variables intuitive and readable. The
variable name should provide some indication as to what the values assigned to it are.
• Your variable names can be any length and can consist of uppercase and lowercase letters
(A-Z, a-z), digits (0-9), and also the underscore character (_). In sum, variable names should
be alphanumeric, but note that even though variable names can contain digits, their first
character can’t be a digit.
• Note: The lower_case_with_underscores naming convention, also known as snake_case,
is commonly used in Python. It isn’t enforced, but it’s a widely adopted standard.
Keywords
• Like any other programming language, Python has a set of special words that are part of its syntax. These
words are known as keywords. To get the complete list of keywords available in your current Python
installation, you can run the following code in an interactive session:
• >>>
• >>> help("keywords")
• Here is a list of the Python keywords. Enter any keyword to get more help.
• False class from or
• None continue global pass
• True def if raise
• and del import return
• as elif in try
• assert else is while
• async except lambda with
• await finally nonlocal yield
• break for not
• There’s another way of getting access to the whole list of Python keywords:
• >>>
• >>> import keyword
• >>> keyword.kwlist
• ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'cla
• ss', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from
• ', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pas
• s', 'raise', 'return', 'try', 'while', 'with', 'yield']
• keyword provides a set of functions that allow you to determine if a given
string is a keyword. For example, keyword.kwlist holds a list of all the
current keywords in Python. These are handy when you need to manipulate
keywords programmatically in your Python programs.
• Here are some examples of valid and invalid variable names in Python:
• >>>
• >>> numbers = [1, 2, 3, 4, 5]
• >>> numbers
• [1, 2, 3, 4, 5]
•
• >>> first_num = 1
• >>> first_num
• 1
•
• >>> 1rst_num = 1
• File "<input>", line 1
• 1rst_num = 1
• ^
• SyntaxError: invalid syntax
•
• >>> π = 3.141592653589793
• >>> π
• 3.141592653589793
Operators
• Operators represent operations, such as addition, subtraction, multiplication, division, and so on. When
you combine them with numbers, they form expressions that Python can evaluate:
• >>>
• >>> # Addition
• >>> 5 + 3
• 8
•
• >>> # Subtraction
• >>> 5 - 3
• 2
•
• >>> # Multiplication
• >>> 5 * 3
• 15
• >>> # Division
• >>> 5 / 3
• 1.6666666666666667
•
• >>> # Floor division
• >>> 5 // 3
• 1
•
• >>> # Modulus (returns the remainder from division)
• >>> 5 % 3
• 2
•
• >>> # Power
• >>> 5 ** 3
• 125
• These operators work with two operands and are commonly known as arithmetic operators. The operands can be
numbers or variables that hold numbers.
• Besides operators, Python provides you with a bunch of built-in
functions for manipulating numbers. These functions are always available to
you. In other words, you don’t have to import them to be able to use them in
your programs.
• Note: There are modules available in the Python standard library, such
as math, that also provide you with functions to manipulate numbers.
• To use the functions associated with these modules, you first have to import
the module and then access the function using module.function_name().
Alternatively, you can import a function directly from the module using:
• from module import function_name.
• Given an integer number or a string representing a number as an argument, float() returns a floating-point number:
• >>>
• >>> # Integer numbers
• >>> float(9)
• 9.0
• >>> float(-99999)
• -99999.0
•
• >>> # Strings representing numbers
• >>> float("2")
• 2.0
• >>> float("-200")
• -200.0
• >>> float("2.25")
• 2.25
•
• >>> # Complex numbers
• >>> float(complex(1, 2))
• Traceback (most recent call last):
• File "<input>", line 1, in <module>
• float(complex(1, 2))
• TypeError: can't convert complex to float
• With float(), you can convert integer numbers and strings representing numbers into floating-point numbers, but you can’t convert a complex number into a floating-
point number.
• Given a floating-point number or a string as an argument, int() returns an integer. This function doesn’t
round the input up to the nearest integer. It simply truncates the input, throwing out anything after the
decimal point, and returns the number. So, an input of 10.6 returns 10 instead of 11. Similarly, 3.25 returns 3:
• >>>
• >>> # Floating-point numbers
• >>> int(10.6)
• 10
• >>> int(3.25)
• 3
•
• >>> # Strings representing numbers
• >>> int("2")
• 2
• >>> int("2.3")
• Traceback (most recent call last):
• File "<input>", line 1, in <module>
• int("2.3")
• ValueError: invalid literal for int() with base 10: '2.3'
•
• Note that you can pass a string representing an integer to int(), but you can’t pass a string representing a
floating-point number. Complex numbers don’t work either.
• Besides these built-in functions, there are a few methods associated with each type of number. You can
access them using attribute reference, also known as dot notation:
• >>>
• >>> 10.0.is_integer()
• True
• >>> 10.2.is_integer()
• False
•
• >>> (10).bit_length()
• 4
• >>> 10.bit_length()
• File "<input>", line 1
• 10.bit_length()
• ^
• SyntaxError: invalid syntax
• These methods can be a useful tool to learn about. In the case of integer numbers, to access their methods
through a literal, you need to use a pair of parentheses. Otherwise, you get a SyntaxError.
Numbers
Floating-point Numbers with decimal points 1.0, 2.2, 42.09, 476.1, -99999.9 float
Complex Numbers with a real part and complex(1, 2), complex(-1, complex
an imaginary part 7), complex("1+2j")
ARTIFICIAL INTELLIGENCE PROGRAMMING
3. Press Enter
Alternatively, you can right-click the Start button and select Windows
PowerShell or Windows PowerShell (Admin).
Python | PowerShell
The most stable Windows downloads are available from the Python for
Windows page. On Windows, you have a choice between 32-bit
(labeled x86) and 64-bit (labeled x86–64) versions, and several flavors
of the installer for each. Underneath the Python Releases for Windows
find the Latest Python 3 Release — Python 3.9.4
Step 2: Download Python Executable Installer and install it
2. Make sure you select the “Install launcher for all users” and “Add
Python 3.9 to PATH” checkboxes.
1. Windows search
2. Type IDLE
3. Open it.
Happy Coding
Pip has not been installed yet if you get the following output:
'pip' is not recognized as an internal or external command,
Operable program or batch file.
Download: Anaconda
Step 2: Select Open Source Distribution
For some or other reason if you are not setting up Python on your
machine, then there are several websites that offer an online Python
interpreter:
Repl.it
Trinket
Python Anywhere
ARTIFICIAL INTELLIGENCE
PROGRAMMING
• If you need to repeat a piece of code several times to get a final result, then
you might need to use a loop.
• Loops are a common way of iterating multiple times and performing some
actions in each iteration. Python provides two types of loops:
• for loops for definite iteration, or performing a set number or repetitions
• while loops for indefinite iteration, or repeating until a given condition is met
• Here’s the general syntax to create a for loop:
• for loop_var in iterable:
• # Repeat this code block until iterable is exhausted
• # Do something with loop_var...
• if break_condition:
• break # Leave the loop
• if continue_condition:
• continue # Resume the loop without running the remaining code
• # Remaining code...
• else:
• # Run this code block if no break statement is run
•
• # Next statement
• This type of loop performs as many iterations as items in iterable. Normally, you use each
iteration to perform a given operation on the value of loop_var. The else clause is optional and
runs when the loop finishes. The break and continue statements are also optional.
• Check out the following example:
• >>>
• >>> for i in (1, 2, 3, 4, 5):
• ... print(i)
• ... else:
• ... print("The loop wasn't interrupted")
• ...
• 1
• 2
• 3
• 4
• 5
• The loop wasn't interrupted
• When the loop processes the last number in the tuple, the flow of execution
jumps into the else clause and prints The loop wasn't interrupted on your
screen.
• That’s because your loop wasn’t interrupted by a break statement. You
commonly use an else clause in loops that have a break statement in their
code block. Otherwise, there’s no need for it.
• If the loop hits a break_condition, then the break statement interrupts the loop
execution and jumps to the next statement below the loop without consuming the
rest of the items in iterable:
• >>>
• >>> number = 3
• >>> for i in (1, 2, 3, 4, 5):
• ... if i == number:
• ... print("Number found:", i)
• ... break
• ... else:
• ... print("Number not found")
• ...
• Number found: 3
• If the loop hits a continue_condition, then the continue statement resumes the
loop without running the rest of the statements in the loop’s code block:
• >>>
• >>> for i in (1, 2, 3, 4, 5):
• ... if i == 3:
• ... continue
• ... print(i)
• ...
• 1
• 2
• 4
• 5
• This time, the continue statement restarts the loop when i == 3. That’s why you
don’t see the number 3 in the output.
While
• You normally use a while loop when you don’t know beforehand how many iterations you need to complete a given
operation. That’s why this loop is used to perform indefinite iterations.
• Here’s the general syntax for a while loop in Python:
• while expression:
• # Repeat this code block until expression is false
• # Do something...
• if break_condition:
• break # Leave the loop
• if continue_condition:
• continue # Resume the loop without running the remaining code
• # Remaining code...
• else:
• # Run this code block if no break statement is run
•
• # Next statement
• This loop works similarly to a for loop, but it’ll keep iterating until expression is false. A common problem
with this type of loop comes when you provide an expression that never evaluates to False. In this case, the
loop will iterate forever.
• Here’s an example of how the while loop works:
• >>>
• >>> count = 1
• >>> while count < 5:
• ... print(count)
• ... count = count + 1
• ... else:
• ... print("The loop wasn't interrupted")
• ...
• 1
• 2
• 3
• 4
• The loop wasn't interrupted
Functions
• In Python, a function is a named code block that performs actions and
optionally computes the result, which is then returned to the calling code.
You can use the following syntax to define a function:
• def function_name(arg1, arg2, ..., argN):
• # Do something with arg1, arg2, ..., argN
• return return_value
• The def keyword starts the function header. Then you need the name of the
function and a list of arguments in parentheses. Note that the list of
arguments is optional, but the parentheses are syntactically required.
ARTIFICIAL INTELLIGENCE
PROGRAMMING
Breadth-first search and Depth-first search in python are algorithms used to traverse a
graph or a tree. They are two of the most important topics that any new python
programmer should definitely learn about. Here we will study what breadth-first search
in python is, understand how it works with its algorithm, implementation with python
code, and the corresponding output to it. Also, we will find out the application and uses
of breadth-first search in the real world.
BFS Algorithm
Before learning the python code for Breadth-First and its output, let us go through the
algorithm it follows for the same. We can take the example of Rubik’s Cube for the
instance. Rubik’s Cube is seen as searching for a path to convert it from a full mess of
colors to a single color. So comparing the Rubik’s Cube to the graph, we can say that
the possible state of the cube is corresponding to the nodes of the graph and the
possible actions of the cube is corresponding to the edges of the graph.
As breadth-first search is the process of traversing each node of the graph, a standard
BFS algorithm traverses each vertex of the graph into two parts: 1) Visited 2) Not
Visited. So, the purpose of the algorithm is to visit all the vertex while avoiding cycles.
BFS starts from a node, then it checks all the nodes at distance one from the beginning
node, then it checks all the nodes at distance two, and so on. So as to recollect the
nodes to be visited, BFS uses a queue.
1. Start by putting any one of the graph’s vertices at the back of the queue.
2. Now take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add those which are not within the
visited list to the rear of the queue.
4. Keep continuing steps two and three till the queue is empty.
Many times, a graph may contain two different disconnected parts and therefore to
make sure that we have visited every vertex, we can also run the BFS algorithm at
every node.
BFS pseudocode
The pseudocode for BFS in python goes as below:
create a queue Q
while Q is non-empty
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
In the above code, first, we will create the graph for which we will use the breadth-first
search. After creation, we will create two lists, one to store the visited node of the graph
and another one for storing the nodes in the queue.
After the above process, we will declare a function with the parameters as visited
nodes, the graph itself and the node respectively. And inside a function, we will keep
appending the visited and queue lists.
Then we will run the while loop for the queue for visiting the nodes and then will remove
the same node and print it as it is visited.
At last, we will run the for loop to check the not visited nodes and then append the same
from the visited and queue list.
As the driver code, we will call the user to define the bfs function with the first node we
wish to visit.
Output
The output of the above code will be as follow:
Example
Let us see how this algorithm works with an example. Here, we will use an undirected
graph with 5 vertices.
We begin from the vertex P, the BFS algorithmic program starts by putting it within the
Visited list and puts all its adjacent vertices within the stack.
Next, we have a tendency to visit the part at the front of the queue i.e. Q and visit its
adjacent nodes. Since P has already been visited, we have a tendency to visit R
instead.
Vertex R has an unvisited adjacent vertex in T, thus we have a tendency to add that to
the rear of the queue and visit S, which is at the front of the queue.
Now, only T remains within the queue since the only adjacent node of S i.e. P is already
visited. We have a tendency to visit it.
Since the queue is empty, we've completed the Traversal of the graph.
Time Complexity
The time complexity of the Breadth first Search algorithm is in the form of O(V+E),
where V is the representation of the number of nodes and E is the number of edges.
Applications
Breadth-first Search Algorithm has a wide range of applications in the real-world. Some
of them are as discussed below:
1. In GPS navigation, it helps in finding the shortest path available from one point
to another.
2. In pathfinding algorithms
3. Cycle detection in an undirected graph
4. In minimum spanning tree
5. To build index by search index
6. In Ford-Fulkerson algorithm to find maximum flow in a network.
Traversal means that visiting all the nodes of a graph which can be done through
Depth-first search or Breadth-first search in python. Depth-first traversal or Depth-first
Search is an algorithm to look at all the vertices of a graph or tree data structure. Here
we will study what depth-first search in python is, understand how it works with its bfs
algorithm, implementation with python code, and the corresponding output to it.
The Depth-First Search is a recursive algorithm that uses the concept of backtracking. It
involves thorough searches of all the nodes by going ahead if potential, else by
backtracking. Here, the word backtrack means once you are moving forward and there
are not any more nodes along the present path, you progress backward on an
equivalent path to seek out nodes to traverse. All the nodes are progressing to be
visited on the current path until all the unvisited nodes are traversed after which
subsequent paths are going to be selected.
DFS Algorithm
Before learning the python code for Depth-First and its output, let us go through the
algorithm it follows for the same. The recursive method of the Depth-First Search
algorithm is implemented using stack. A standard Depth-First Search implementation
puts every vertex of the graph into one in all 2 categories: 1) Visited 2) Not Visited. The
only purpose of this algorithm is to visit all the vertex of the graph avoiding cycles.
1. We will start by putting any one of the graph's vertex on top of the stack.
2. After that take the top item of the stack and add it to the visited list of the vertex.
3. Next, create a list of that adjacent node of the vertex. Add the ones which aren't
in the visited list of vertexes to the top of the stack.
4. Lastly, keep repeating steps 2 and 3 until the stack is empty.
DFS pseudocode
The pseudocode for Depth-First Search in python goes as below: In the init() function,
notice that we run the DFS function on every node because many times, a graph may
contain two different disconnected part and therefore to make sure that we have visited
every vertex, we can also run the DFS algorithm at every node.
DFS(G, u)
u.visited = true
if v.visited == false
DFS(G,v)
init() {
For each u ∈ G
u.visited = false
For each u ∈ G
DFS(G, u)
}
DFS Implementation in Python (Source Code)
Consider the following graph which is implemented in the code below:
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
In the above code, first, we will create the graph for which we will use the depth-first
search. After creation, we will create a set for storing the value of the visited nodes to
keep track of the visited nodes of the graph.
After the above process, we will declare a function with the parameters as visited
nodes, the graph itself and the node respectively. And inside the function, we will check
whether any node of the graph is visited or not using the “if” condition. If not, then we
will print the node and add it to the visited set of nodes.
Then we will go to the neighboring node of the graph and again call the DFS function to
use the neighbor parameter.
At last, we will run the driver code which prints the final result of DFS by calling the DFS
the first time with the starting vertex of the graph.
Output
The output of the above code is as follow:
Example
Let us see how the DFS algorithm works with an example. Here, we will use an
undirected graph with 5 vertices.
We begin from the vertex P, the DFS rule starts by putting it within the Visited list
and putting all its adjacent vertices within the stack.
Next, we tend to visit the part at the highest of the stack i.e. Q, and head to its adjacent
nodes. Since P has already been visited, we tend to visit R instead.
Vertex R has the unvisited adjacent vertex in T, therefore we will be adding that to the
highest of the stack and visit it.
At last, we will visit the last component S, it does not have any unvisited adjacent
nodes, thus we've completed the Depth First Traversal of the graph.
Time Complexity
The time complexity of the Depth-First Search algorithm is represented within the sort
of O(V + E), where V is that the number of nodes and E is that the number of edges.
Applications
Depth-First Search Algorithm has a wide range of applications for practical purposes.
Some of them are as discussed below:
Logic Programming uses facts and rules for solving the problem. That is why they are
called the building blocks of Logic Programming. A goal needs to be specified for every
program in logic programming. To understand how a problem can be solved in logic
programming, we need to know about the building blocks − Facts and Rules −
Facts
Actually, every logic program needs facts to work with so that it can achieve the given
goal. Facts basically are true statements about the program and data. For example, Delhi
is the capital of India.
Rules
Actually, rules are the constraints which allow us to make conclusions about the problem
domain. Rules basically written as logical clauses to express various facts. For example,
if we are building any game then all the rules must be defined.
Rules are very important to solve any problem in Logic Programming. Rules are basically
logical conclusion which can express the facts. Following is the syntax of rule −
A∶− B1,B2,...,Bn.
Here, A is the head and B1, B2, ... Bn is the body.
For example − ancestor(X,Y) :- father(X,Y).
ancestor(X,Z) :- father(X,Y), ancestor(Y,Z).
This can be read as, for every X and Y, if X is the father of Y and Y is an ancestor of Z, X
is the ancestor of Z. For every X and Y, X is the ancestor of Z, if X is the father of Y and
Y is an ancestor of Z.
Program or Solution
n = int(input())
count = 0
while n > 0:
n = n // 10
count = count + 1
print(count)
Program Explanation
if we divide a number by 10, then last digit of the same number will removed and we get
remaining digits as output. Do the same till number becomes 0 and count iteration. So the
count is number of digits of the given number .
Program or Solution
Program or Solution
Program Explanation
initialize total is equal to 0
calculate the remainder of a number by doing number % 10, add the remainder to total and
divide the number by the 10 and repeat the above steps till number becomes zero.
Print the total, you will get the sum of digits of the number
Output
Program Explanation
initialize total is equal to 0
calculate the remainder of a number by doing number % 10, add the remainder to (total *
10) and divide the number by the 10 and repeat the above steps till number becomes zero.
Print the total, you will get the sum of digits of the number.
Program or Solution
secret_number = randint(1,5)
if secret_number == guess_number:
else:
Program Explanation
Line 3: Imports the randint function from the package random
Line 5: using randint system generates a secret number
Line 7 : getting a guess from user
line 9 : check whether secret number generated by system and guessing number entered by
user are same
line 10 : if same, display "your guess is correct"
line 12 : if not same, display "your guess is wrong"
At each stage the points will be awarded to user based on following condition
Solved in points
first attempt 100
second attempt 75
third attempt 50
fourth attempt 25
fifth attempt 10
Program or Solution
level = 1
points = [100,75,50,25,10]
points_scored = list()
end_value = level * 10
secret_number = randint(1,end_value)
if secret_number == guess_number:
points_scored.append(points[counter])
level = level + 1
break
else:
else:
break
else:
for i in range(0,3):
print("level {} points {}".format(i+1, points_scored[i])) '''
Program Explanation
Logic is same as level 4, in addition,
points are stored using list
points_scored variable is a list which stores the points scored by user at each stage
the final for loop shows the points scored by user at each stage.
Program or Solution
Program Explanation
Prime numbers are numbers those only divisible by 1 and same. using a outer for loop we
check take every number n from x to y
Inner for loop checks each number is prime or not, if prime it prints the n.
102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},
104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}
3. Check Stock
a. Display the items and available quantity
b. Highlight the items which are available less than 5 kgs.
Program or Solution
items = {
101:{'item_name':'Apple','Quantity_in_kgs':50,'Price_per_kg':200},
102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},
104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}
trans = {}
#Stock Printing
def stock_check():
print("Item Name | Available Stock")
for item_id in items:
if items[item_id]['Quantity_in_kgs'] <= 5:
print("----------------------------------------")
print("| ",items[item_id]['item_name'], " | ",items[item_id]['Quantity_in
_kgs']," |")
print("----------------------------------------")
else:
print("| ",items[item_id]['item_name'], " | ",items[item_id]['Quantity_in
_kgs']," |")
#Add New Item to Database
def add_new_item():
item_ids = list(items.keys())
item_id = max(item_ids) + 1
item_name = input("Enter Item Name:")
price = int(input("Enter Price Per Kilo Gram:"))
quantiy = int(input("Enter Quantity"))
item = {'item_name':item_name,'Quantity_in_kgs':quantiy,'Price_per_kg':price}
items[item_id]= item
print('Item Added')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", item_name, " | ", quantiy, " | ", price)
#Update the Quantity of Existing Item
def update_item(item_id):
quantiy = int(input("Enter Quantity"))
items[item_id]['Quantity_in_kgs'] = items[item_id]['Quantity_in_kgs'] + quantiy
print('Item Updated')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", items[item_id]['item_name'], " | ", items[item_id]['Quantit
y_in_kgs'], " | ", items[item_id]['Price_per_kg'] )
#Stock Entry
def add_item():
item_name = input("Enter the Item Name")
print("item id | item name")
print("-----------------")
for item in items:
if item_name in items[item]['item_name']:
print(item, " | ", items[item]['item_name'])
trans_ids = list(trans.keys())
if len(trans_ids) == 0:
trans_id = 201
else:
trans_id = max(trans_ids) + 1
sale(trans_id)
elif choice == 3:
stock_check()
elif choice == 4:
break
else:
print("Invalid Choice")
Program Explanation
add_item() method checks whether the item is existing item or new item to the fruit shop.
if item is new then it calls add_new_item() method else it call update_item() method.
sale() method gets detail of each item and fetch price from dictionary to calculate amount.
amount will be added to the total. Sale() method finally decrease the sold quantity in item
dictionary.
stock_check() method prints all items and its available quantity.