0% found this document useful (0 votes)
7 views27 pages

Ai File (Akash 3674)

Ai practical file

Uploaded by

doffy1845
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)
7 views27 pages

Ai File (Akash 3674)

Ai practical file

Uploaded by

doffy1845
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/ 27

PRACTICAL FILE OF

ARTIFICIAL INTELLIGENCE & SOFT COMPUTING LABORATOR

(PGCA1929)

JULY-DECEMBER 2024

SUBMITTED BY: AKASH SUBMITTED TO: PROF. RAJNI PURI


MCA 2sem (Dept. Of Computer Application)
(2309931)

DEPARTMENT OF COMPUTER APPLICATIONS


GUJRANWALA GURU NANAK INSTITUTE OF
MANAGEMENT & TECHNOLOGY
Civil Lines, Ludhiana

1|GGNIMT
Index
Sr. No. Topic Pg. No.
1. Basic definition, Characteristic of artificial intelligence 3
2. History of artificial intelligence 4–5
Foundation of artificial intelligence & Types of artificial
3. 6–7
intelligence
4. Application of artificial intelligence 8–9
5. Water jug program 10 – 11
6. 8 Puzzle program 12 – 13
7. Python program for working of And gate 14
8. Python program for swapping of two variable 15
9. Python program to find largest number 16
10. Python program of Fibonacci sequence 17
11. (BFS) Breadth first search technique 18
12. Python program for And gate using perceptron 19
13. Python program for text to speech conversion 20
14. Tokenization 21
15. Python program to check prime number 22
16. Python program to create calculator 23 – 24
17. Python program to swapping a number 25
18. Python program to find factorial of number 26
19. Python program for sorting of array 27

1. Basic definition, Characteristic of Artificial Intelligence

2|GGNIMT
INTELLIGENCE:

Intelligence is a general mental ability that involves reasoning, problem solving, and learning. It also
integrates cognitive functions such as memory, attention, perception, language, and planning.

ARTIFICIAL INTELLIGENCE (AI):

Artificial intelligence is the simulation of human intelligence processes by machines, especially computer
systems. Specific applications of AI include expert systems, natural language processing, and speech
recognition and machine vision. Artificial intelligence (AI) refers to the simulation of human intelligence in
machines that are programmed to think like humans and mimic their actions. The term may also be
applied to any machine that exhibits traits associated with a human mind such as learning and problem
solving.

CHRACTERISCS OF ARTIFICIAL INTELLIGENCE:

 Reasoning
 Learning
 Perception
 Problem Solving
 Linguistic Intelligence

Reasoning: Reasoning plays a great role in the process of artificial Intelligence. Thus Reasoning can be
defined as the logical process of drawing conclusions, making predictions or constructing approaches
towards a particular thought with the help of existing knowledge.

Learning: Learning is a process that leads to change, which occurs as a result of experience and increases
the potential for improved performance and future learning.

Perception: Perception is the process by which sensory information captured in the real world is
interpreted, acquired, selected, and then organized. Human beings, for example, have sensory receptors
for touch, taste, smell, sight, and hearing

Problem Solving: Problem solving is the act of defining a problem; determining the cause of the problem;
identifying, prioritizing, and selecting alternatives for a solution; and implementing a solution

Linguistic Intelligence: It is one's ability to use, comprehend, speak, and write the verbal and written
language. Natural Language Processing (NLP) is an area of AI that draws on computer science and
computational linguistics to fill the gap between human communication and computer understanding.

2. History of Artificial Intelligence


3|GGNIMT
Maturation of Artificial Intelligence (1943-1952):
 Year 1943: The first work which is now recognized as AI was done by Warren McCulloch and
Walter pits in 1943. They proposed a model of artificial neurons.
 Year 1949: Donald Hebb demonstrated an updating rule for modifying the connection strength
between neurons. His rule is now called Hebbian learning.
 Year 1950: The Alan Turing who was an English mathematician and pioneered Machine learning in
1950. Alan Turing publishes "Computing Machinery and Intelligence" in which he proposed a test.
The test can check the machine's ability to exhibit intelligent behavior equivalent to human
intelligence, called a Turing test

The Birth of Artificial Intelligence (1952-1956):

 Year 1955: An Allen Newell and Herbert A. Simon created the "first artificial intelligence program
“Which was named as "Logic Theorist". This program had proved 38 of 52 Mathematics theorems,
and find new and more elegant proofs for some theorems.
 Year 1956: The word "Artificial Intelligence" first adopted by American Computer scientist John
McCarthy at the Dartmouth Conference. For the first time, AI coined as an academic field. At that
time high-level computer languages such as FORTRAN, LISP, or COBOL were invented. And the
enthusiasm for AI was very high at that time.

The Golden Years-Early Enthusiasm (1956-1974):

 Year 1966: The researchers emphasized developing algorithms which can solve mathematical
problems. Joseph Weizenbaum created the first chatbot in 1966, which was named as ELIZA.
 Year 1972: The first intelligent humanoid robot was built in Japan which was named as WABOT-1.

The First AI Winter (1974-1980):

 The duration between years 1974 to 1980 was the first AI winter duration. AI winter refers to the
time period where computer scientist dealt with a severe shortage of funding from government
for AI researches. During AI winters, an interest of publicity on artificial intelligence was
decreased.

A Boom of AI (1980-1987):

 Year 1980: After AI winter duration, AI came back with "Expert System". Expert systems were
programmed that emulate the decision-making ability of a human expert.
 In the Year 1980, the first national conference of the American Association of Artificial Intelligence
was held at Stanford University

The Second AI Winter (1987-1993):

 The duration between the years 1987 to 1993 was the second AI Winter duration. Again Investors
and government stopped in funding for AI research as due to high cost but not efficient result. The
expert system such as XCON was very cost effective

The Emergence of Intelligent Agents (1993-2011):

4|GGNIMT
 Year 1997: In the year 1997, IBM Deep Blue beats world chess champion, Gary Kasparov, and
became the first computer to beat a world chess champion.
 Year 2002: for the first time, AI entered the home in the form of Roomba, a vacuum cleaner.
 Year 2006: AI came in the Business world till the year 2006. Companies like Facebook, Twitter, and
Netflix also started using AI.

Deep Learning, Big Data And Artificial General Intelligence (2011-Present):

 Year 2011: In the year 2011, IBM's Watson won jeopardy, a quiz show, where it had to solve the
complex questions as well as riddles. Watson had proved that it could understand natural
language and can solve tricky questions quickly.
 Year 2012: Google has launched an Android app feature "Google now", which was able to provide
information to the user as a prediction.
 Year 2014: In the year 2014, Chatbot "Eugene Goostman" won a competition in the infamous
"Turing test."
 Year 2018: The "Project Debater" from IBM debated on complex topics with two master debaters
and also performed extremely well.

Google has demonstrated an AI program "Duplex" which was a virtual assistant and which had taken
hairdresser appointment on call and lady on other side didn't notice that she was talking with the machine

3. Foundation of Artificial Intelligence


5|GGNIMT
 Acting humanly (The Turing Test approach): This approach was designed by Alan Turing. The
ideology behind this approach is that a computer passes the test if a human interrogator, after
asking some written questions, cannot identify whether the written responses come from a
human or from a computer.
 Thinking humanly (The cognitive modeling approach): The idea behind this approach is to
determine whether the computer thinks like a human.
 Thinking rationally (The “laws of thought” approach ): The idea behind this approach is to
determine whether the computer thinks rationally i.e. with logical reasoning.
 Acting rationally (The rational agent approach ): The idea behind this approach is to determine
whether the computer acts rationally i.e. with logical reasoning.

TYPES OF ARTIFICIAL INTELLIGENCE:

 Artificial Narrow Intelligence


 Artificial General Intelligence
 Artificial Super Intelligence

Artificial Narrow Intelligence (ANI):

 Artificial Narrow Intelligence or ANI is also referred to as Narrow AI or weak AI. Weak AI or Narrow
AI is specifically goal-oriented, that is used to design to perform singular tasks such as face
recognition, driving car, speech recognition/voice assistants, or browsing the Internet.
 Narrow AI cannot replicate human intelligence, it just simulates human behavior which is based
on a narrow range of contexts and parameters or factors.
 Narrow AI makes use of NLP to perform tasks, which means that it understands text and speech in
natural language and it is programmed to communicate with humans in a personalized manner.
 The examples of narrow AI manufacturing and drone robots, IBM’s Watson, Siri by Apple, Alexa by
Amazon, Cortana by Microsoft, and other virtual assistants

Artificial General Intelligence (AGI):

 Also referred to as Strong AI/Deep AI, AGI is a concept of a machine that possesses general
intelligence that can mimic human behavior or intelligence and is capable of learning and applying
this knowledge to solve any problem. AGI is capable of thinking, understanding, and acting in a
way that is identical to humans in any given scenario.

 AGI is not yet achieved by AI researchers and scientists. To achieve AGI, they need to program all
the cognitive abilities into the machine. Machines are required to take up experiential learning to
the higher levels and apart from improving efficiency in singular tasks; they also need to be
capable of applying knowledge to a wider area of solving problems.

 Strong AI makes use of the theory of mind AI framework. It is the ability to anticipate the needs,
beliefs, emotions, thought processes of other intelligent entities. It focuses not on simulation or
replication, but on truly understanding humans.

6|GGNIMT
 The example of strong AI includes Fujitsu-built K, a supercomputer, which is one of the most
remarkable attempts towards achieving strong AI, but considering some disappointing factors, it is
not easy to say that strong AI can be achieved in near future.

Artificial Super Intelligence (ASI):

 Apart from understanding human behavior, AI where machines surpass the capability of human
intelligence and become self-aware is the area that is called Artificial Super Intelligence.

 The concept of ASI includes evoking emotions, requirements, beliefs, and impulses of its own.
Besides replicating human intelligence, it is anticipated that ASI would theoretically be far better
than humans in areas like math, sports, science, medicine, art, hobbies, emotional relationships,
or simply everything. If such super intelligent machines came into existence, it will impact
humanity, our survival, or our lifestyle

7|GGNIMT
4. Application of Artificial Intelligence

1. AI in Astronomy :
 Artificial Intelligence can be very useful to solve complex universe problems. AI technology can be
helpful for understanding the universe such as how it works, origin, etc.

2. AI in Healthcare:
 In the last, five to ten years, AI becoming more advantageous for the healthcare industry and
going to have a significant impact on this industry.
 Healthcare Industries are applying AI to make a better and faster diagnosis than humans. AI can
help doctors with diagnoses and can inform when patients are worsening so that medical help can
reach to the patient before hospitalization.

3. AI in Gaming:
 AI can be used for gaming purpose. The AI machines can play strategic games like chess, where
the machine needs to think of a large number of possible places.

4. AI in Finance:
 AI and finance industries are the best matches for each other. The finance industry is
implementing automation, chatbot, adaptive intelligence, algorithm trading, and machine learning
into financial processes.

5. AI in Data Security:
 The security of data is crucial for every company and cyber-attacks are growing very rapidly in the
digital world. AI can be used to make your data more safe and secure.
 Some examples such as AEG bot, AI2 Platform, are used to determine software bug and cyber-
attacks in a better way.

6. AI in Social Media:
 Social Media sites such as Facebook, Twitter, and Snapchat contain billions of user profiles, which
need to be stored and managed in a very efficient way.
 AI can organize and manage massive amounts of data.
 AI can analyze lots of data to identify the latest trends, hashtag, and requirement of different
users.

7. AI in Travel & Transport:


 AI is becoming highly demanding for travel industries. AI is capable of doing various travel related
works such as from making travel arrangement to suggesting the hotels, flights, and best routes to
the customers.
 Travel industries are using AI-powered chatbots which can make human-like interaction with
customers for better and fast response.
8. AI in Entertainment:
 We are currently using some AI based applications in our daily life with some entertainment
services such as Netflix or Amazon. With the help of ML/AI algorithms, these services show the
recommendations for programs or shows.

9. AI in Automotive Industry:
8|GGNIMT
 Some Automotive industries are using AI to provide virtual assistant to their user for better
performance. Such as Tesla has introduced TeslaBot, an intelligent virtual assistant.  Various
Industries are currently working for developing self-driven cars which can make your journey more
safe and secure.

10. AI in Robotics:
 Artificial Intelligence has a remarkable role in Robotics. Usually, general robots are programmed
such that they can perform some repetitive task, but with the help of AI, we can create intelligent
robots which can perform tasks with their own experiences without pre-programmed.
 Humanoid Robots are best examples for AI in robotics, recently the intelligent Humanoid robot
named as Erica and Sophia has been developed which can talk and behave like humans.

11. AI in Agriculture:
 Agriculture is an area which requires various resources, labor, money, and time for best result.
Now a day's agriculture is becoming digital, and AI is emerging in this field. Agriculture is applying
AI as agriculture robotics, solid and crop monitoring, predictive analysis. AI in agriculture can be
very helpful for farmers.

12. AI in E-commerce:
 AI is providing a competitive edge to the e-commerce industry, and it is becoming more
demanding in the e-commerce business. AI is helping shoppers to discover associated products
with recommended size, color, or even brand.

13. AI in Education:
 AI can automate grading so that the tutor can have more time to teach. AI chatbot can
communicate with students as a teaching assistant.
 AI in the future can be work as a personal virtual tutor for students, which will be accessible easily
at any time

5. Water Jug Problem


9|GGNIMT
You are given two jug, a 4-gallon one and a 3-gallon one. Neither has any measuring mark on it. There is a
pump that can be used to fill the jugs with water. How can you get exactly 2 gallons of water into the 4-
gallon jug.

The state space for this problem can be described as the set of ordered pair of integers (x,y)

Where,
X represents the quantity of water in the 4-gallon jug X = 0,1,2,3,4
Y represent the quantity of water in 3-gallon jug Y = 0,1,2,3

Start State: (0,0)


Goal State: (2,0)

Python Code Of Water Jug Problem

j1=0
j2=0
x=4
y=3
print("Initial state=(0,0)")
print("Capacities=(4,3)")
print("Goal state=(2,0)")
while (j1 !=2):
r=int(input("Enter rule: "))
if(r==0 or r>8):
print("enter a valid input")
else:
if(r==1):
j1=x
elif(r==2):
j2=y
elif(r==3):
j1=0
elif(r==4):
j2=0
elif(r==5):
t=y-j2
j2=y
j1-=t
if j1<0:
j1=0
elif(r==6):
t=x-j1
j1=x
j2-=t

if j2<0:
j2=0
elif(r==7):
10 | G G N I M T
j2+=j1
j1=0
if j2>y:
j2=y
elif(r==8):
j1+=j2
j2=0
if j1>x:
j1=x
print (j1,j2)

Output:-

Initial state=(0,0)
Capacities=(4,3)
Goal state=(2,0)
Enter rule: 2
03
Enter rule: 8
30
Enter rule: 2
33
Enter rule: 6
42
Enter rule: 3
02
Enter rule: 8
20

6. Python Program For 8 Puzzle Problem


def print_in_format(matrix):
11 | G G N I M T
for i in range(9):
#print a new line in after every 3 tiles are printed
if i%3 == 0 and i > 0:
print("")
#Print the tile
print(str(matrix[i])+" ", end = "")
#Counts the heuristic value for a state of the 8 puzzle
def count(s):
#heuristic value counting variable
c=0
#Solved state of a 8 puzzle
ideal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
#Loop that iterates through all the tiles of unsolved puzzle and compares them with
#the solved one's. if they don't match, then increase the heuristic value count by 1
for i in range(9):
if s[i] != 0 and s[i] != ideal[i]:
c += 1
#return the counted heuristic value
return c
#The movement function that moves the blank tile to possible positions
#and compares the moved states for the minimum heuristic valued state
def move(ar, p, st):
#variable that stores minimum heuristic value of a moved state
rh = 999999
#Copy the puzzle state to another list variable to be used in here
store_st = st.copy()
#Loop that makes moves of blank tiles to all possible positions
for i in range(len(ar)):
#Copying the current puzzle state to another list variable to be
#used in the swapping blank tile operation
dupl_st = st.copy()
#swapping the blank tile
temp = dupl_st[p]
dupl_st[p] = dupl_st[arr[i]]
dupl_st[arr[i]] = temp
#counting the heuristic value for swaped puzzle stat
tmp_rh = count(dupl_st)
#if current swaped puzzle state has the less heuristic value than
#the before one, then store current state and current heuristic value
if tmp_rh < rh:
rh = tmp_rh
store_st = dupl_st.copy()
#return the state with the minimum heuristic value along with the heuristic value
return store_st, rh
#Unsolved 8 Puzzle stored in list 'state' state = [1, 2, 3, 0, 5, 6, 4, 7, 8]
h = count(state)
Level = 1

#initial printing of current state of 8 puzzle


print("\n------ Level "+str(Level)+" ------")
print_in_format(state)
print("\nHeuristic Value(Misplaced) : "+str(h))
12 | G G N I M T
while h>0:
pos = int(state.index(0))
#Increasing level as one level of search is executing now
Level += 1
if pos == 0:
arr = [1, 3]
state, h = move(arr, pos, state)
elif pos == 1:
arr = [0, 2, 4]
state, h = move(arr, pos, state)
elif pos==2:
arr = [1, 5]
state, h = move(arr, pos, state)
elif pos==3:
arr = [0, 4, 6]
state, h = move(arr, pos, state)
elif pos==4:
arr = [1, 3, 5, 7]
state, h = move(arr, pos, state)
elif pos==5:
arr = [2, 4, 8]
state, h = move(arr, pos, state)
elif pos==6:
arr = [3, 7]
state, h = move(arr, pos, state)
elif pos==7:
arr = [4, 6, 8]
state, h = move(arr, pos, state)
elif pos==8:
arr = [5, 6]
state, h = move(arr, pos, state)
print("\n------ Level "+str(Level)+" ------")
print_in_format(state)
print("\nHeuristic Value(Misplaced) : "+str(h))

Output:-

7. Python Program For Working of And Gate

13 | G G N I M T
def AND (a, b):

if a == 1 and b == 1:
return True
else:
return False

# Driver code
if __name__=='__main__':
print(AND(1, 1))

print("+---------------+----------------+")
print(" | AND Truth Table | Result |")
print(" A = False, B = False | A AND B =",AND(False,False)," | ")
print(" A = False, B = True | A AND B =",AND(False,True)," | ")
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")

Output:-

True
+---------------+----------------+
| AND Truth Table | Result |
A = False, B = False | A AND B = False |
A = False, B = True | A AND B = False |
A = True, B = False | A AND B = False |
A = True, B = True | A AND B = True |

8. Python Program Swapping of two Variable

14 | G G N I M T
x=5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Output:-

The value of x after swapping: 10


The value of y after swapping: 5

9. Python Program To Find Largest Number


15 | G G N I M T
n = int(input("Enter the number of values: "))

numbers = []

for i in range(n):

num = float(input(f"Enter number {i+1}: "))

numbers.append(num)

largest_number = max(numbers)

print("The largest number is:", largest_number)

Output:-

Enter the number of values: 4


Enter number 1: 5
Enter number 2: 10
Enter number 3: 3
Enter number 4: 0
The largest number is: 10.0

10. Python Program of Fibonacci Sequence


16 | G G N I M T
#Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms

n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:-

How many terms? 8


Fibonacci sequence:
0
1
1
2
3
5
8
13

11. Python Code Of BFS


17 | G G N I M T
Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts
at the tree root (or some arbitrary node of a graph, sometimes referred to as a ‘search key’), and explores
all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. It is
implemented using a queue.

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')

Output:-

Following is the Breadth-First Search


537248

12. Python Program For And Gate Using Perceptron

18 | G G N I M T
w1, w2, b = 0.5, 0.5, -1

def activate(x):
return 1 if x >= 0 else 0
def train_perceptron(inputs, desired_outputs, learning_rate, epochs):
global w1, w2, b
for epoch in range(epochs):
total_error = 0
for i in range(len(inputs)):
A, B = inputs[i]
target_output = desired_outputs[i]
output = activate(w1 * A + w2 * B + b)
error = target_output - output
w1 += learning_rate * error * A
w2 += learning_rate * error * B
b += learning_rate * error
total_error += abs(error)
if total_error == 0:
break
inputs = [(0, 0), (0, 1), (1, 0), (1, 1)]
desired_outputs = [0, 0, 0, 1]
learning_rate = 0.1
epochs = 100
train_perceptron(inputs, desired_outputs, learning_rate, epochs)
for i in range(len(inputs)):
A, B = inputs[i]
output = activate(w1 * A + w2 * B + b)
print(f"Input: ({A}, {B}) Output: {output}")

Output:-

Input: (0, 0) Output: 0


Input: (0, 1) Output: 0
Input: (1, 0) Output: 0
Input: (1, 1) Output: 1

13. Python Program For Text To Speech Conversion

19 | G G N I M T
from gtts import gTTS

# This module is imported so that we can


# play the converted audio
import os

# The text that you want to convert to audio


mytext = 'Welcome to geeksforgeeks Joe!'

# Language in which you want to convert


language = 'en'

# Passing the text and language to the engine,


# here we have marked slow=False. Which tells
# the module that the converted audio should
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)

# Saving the converted audio in a mp3 file named


# welcome
myobj.save("welcome.mp3")

# Playing the converted file


os.system("start welcome.mp3")

14. Tokenization

20 | G G N I M T
It's the process of breaking a stream of textual data into words, terms, sentences, symbols, or some other
meaningful elements called tokens. A lot of open-source tools are available to perform the tokenization
process.

Tokenization is a common task in Natural Language Processing (NLP). It’s a fundamental step in both
traditional NLP methods like Count Vectorizer and Advanced Deep Learning-based architectures like
Transformers.

Tokenization is a way of separating a piece of text into smaller units called tokens. Here, toke ns can be
either words, characters, or subwords. Hence, tokenization can be broadly classified into 3 types – word,
character, and subword (n-gram characters) tokenization.

PYTHON CODE FOR TOKENIZING TEXT DATA:

import nltk

file=open("token.txt","r",encoding="UTF-8")

text=file.read()text=text.replace("\n","")

nltk.download("punkt")

tokenizer=nltk.data.load("tokenizers/punkt/english.pickle")

sentences=tokenizer.tokenize(text) print(sentences)

Output:-

15. Python Program To Check Prime Number


21 | G G N I M T
A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.
Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is
called a prime number

Python Code To Check Prime Number

def is_prime(num):
if num <= 1:
return False
for i in range(2,num):
if num % i == 0:
return False
return True

number = int(input("Enter a number: "))


if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

Output:-

Enter a number: 2
2 is a prime number.
Enter a number: 20
20 is not a prime number.

16. Python Program To Create Calculator


22 | G G N I M T
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
23 | G G N I M T
if next_calculation == "no":
break
else:
print("Invalid Input")

Output:-

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter first number: 10
Enter second number: 5
10.0 + 5.0 = 15.0
Let's do next calculation? (yes/no): yes
Enter choice(1/2/3/4): 2
Enter first number: 5
Enter second number: 2
5.0 - 2.0 = 3.0
Let's do next calculation? (yes/no):

17. Python Program Swapping of Number


24 | G G N I M T
x=5

y = 10

# To take inputs from the user

#x = input('Enter value of x: ')

#y = input('Enter value of y: ')

# create a temporary variable and swap the values

temp = x

x=y

y = temp

print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))

Output:-

The value of x after swapping: 10


The value of y after swapping: 5

18. Python Program To Find Factorial Number

25 | G G N I M T
def fact(n):

result=1

if n<=1:

return result

else:

for i in range(1,n+1):

result=result*i;

return result

number =7

print(f" Factorial of {number} is {fact(number)}")

Output:-

Factorial of 7 is 5040

19. Python Program For Sorting of Array

26 | G G N I M T
a=(1,11,5,7,9,3,2)

x=sorted(a)

print(x)

Output:-

[1, 2, 3, 5, 7, 9, 11]

27 | G G N I M T

You might also like