[go: up one dir, main page]

0% found this document useful (0 votes)
53 views25 pages

Ai Lab Manual

Uploaded by

gpswesley
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)
53 views25 pages

Ai Lab Manual

Uploaded by

gpswesley
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/ 25

QIS COLLEGE OF ENGINEERING AND TECHNOLOGY

Vengamukkapalem- 523272, Ongole, Andhra Pradesh


(AUTONOMOUS)

DEPARTMENT OF AIMLDS

Vision:
To facilitate transformation of students into highly skilled, knowledgeable and
competent software professional focusing on ethical values and societal
commitment.

Mission:

 To impart quality education to meet the needs of the industry and research in the field of
computer science and engineering.
 To encourage an environment conductive to innovation, creativity, team spirit and
entrepreneurial leadership in Computer Science and Engineering.
 To foster networking with Alumni, Software Industries, Institutes and other stakeholders
for effective interaction.
 To practice and promote high standards of ethical values through societal commitment.

PEO’s (PROGRAMME EDUCATIONAL OBJECTIVES):

1. PEO1. Graduates will have solid foundation in fundamentals of computer science and
engineering required to solve computing problems and create innovative software products and
solutions for the real life problems.
2. PEO2. Graduates will have technical competence and skills to use modern and cost-effective
tools and technologies and have extensive and effective practical skills in computer science and
engineering to pursue a career as a computer engineer.
3. PEO3. Graduates will have attributes like professionals with world class academic excellence,
ethics, best practices, values, social concerns, lifelong learning and openness to other
international cultures to meet the global needs.
4. PEO4. Graduates will have managerial and entrepreneur skills with cross-cultural etiquettes,
leading to a sustainable competitive edge in R&D and meeting societal needs.
Program Outcomes
PO1 Engineeringknowledge:Applytheknowledgeofmathematics,science,engineeringfundamentals,and
an engineeringspecializationtothesolutionofcomplex engineering problems.
PO2 Problemanalysis:Identify,formulate,reviewresearchliterature,andanalyzecomplexengineeringproble
msreachingsubstantiatedconclusionsusingfirstprinciplesofmathematics,naturalsciences,andengineeri
ngsciences.
PO3 Design/developmentofsolutions:Design solutions for complex engineering problems and design
systemcomponentsorprocessesthatmeetthespecifiedneedswithappropriateconsiderationforthepublich
ealthandsafety,andthecultural,societal,andenvironmentalconsiderations.
PO4 Conductinvestigationsofcomplexproblems:Useresearch-
basedknowledgeandresearchmethodsincludingdesignofexperiments,analysisandinterpretationofdata,
andsynthesisoftheinformationtoprovidevalidconclusions.
PO5 Moderntoolusage:Create,select,andapplyappropriatetechniques,resources,andmodernengineeringan
dITtoolsincludingpredictionandmodelingtocomplexengineeringactivitieswithanunderstandingoftheli
mitations.
PO6 Theengineerandsociety:Applyreasoninginformedbythecontextualknowledgetoassesssocietal,health
,safety,legalandculturalissuesandtheconsequentresponsibilitiesrelevanttotheprofessionalengineering
practice.
PO7 Environmentandsustainability:Understandtheimpactoftheprofessionalengineeringsolutionsinsocie
talandenvironmentalcontexts,anddemonstratetheknowledgeof,andneedforsustainabledevelopment.

PO8 Ethics:Applyethicalprinciplesandcommittoprofessionalethicsandresponsibilitiesandnormsoftheengi
neeringpractice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader
indiverse teams, and in multi disciplinary settings.
PO10 Communication:Communicateeffectivelyoncomplexengineeringactivitieswiththeengineeringcomm
unityandwithsocietyatlarge,suchas,beingabletocomprehendandwriteeffectivereportsanddesigndocu
mentation,makeeffectivepresentations,andgiveandreceiveclearinstructions.
PO11 Projectmanagementandfinance:Demonstrateknowledgeandunderstandingoftheengineeringandma
nagementprinciplesandapplythesetoone’sownwork,asamemberandleaderinateam,tomanageprojectsa
ndinmultidisciplinaryenvironments.
PO12 Life-
longlearning:Recognizetheneedfor,andhavethepreparationandabilitytoengageinindependentandlife-
longlearninginthebroadestcontextoftechnologicalchange.
Program Specific Outcomes
PSO1 Domain Knowledge: An ability to understand, analyze and develop computer programs in the
areas related to Algorithms, System Software, Multimedia, Web Design, Big Data and Analytics
and Networking for efficient design of computer based systems of varying complexity to meet the
need of the software industry.
PSO2
1. Process Management: An Ability to organize and apply standard practices and strategies in
software product development by managing and monitoring the resources and safeguarding the
data.
ARTIFICIAL INTELLIGENCE LAB SYLLABUS

Sl. No. List of Experiments Page No.


1 (a). Write a python program to print the multiplication table for the given
number. 6
(b). Write a python program to check whether the given number is prime or
not.
(c) Write a python program to find factorial of the given number.
2
9
Write a python program to implement simple Chatbot.
3 (a) Write a python program to implement List operations (Nested List, 10
Length, Concatenation, Membership, Iteration, Indexing and Slicing).
(b) Write a python program to implement List methods (Add, Append, and
Extend & Delete).

4 (a) Write a python program to Illustrate Different Set Operations. 13


(b) Write a python program to generate Calendar for the given month and
year.
(c) Write a python program to implement Simple Calculator program.

5 (a) Write a python program to Add Two Matrices. 19


(b) Write a python program to Transpose a Matrix.

6 Write a python program to implement Breadth First Search Traversal. 22

7 Write a python program to implement Water Jug Problem. 24

8 (a) Write a python program to remove punctuations from the given string. 26
(b) Write a python program to sort the sentence in alphabetical order.

9 Write a program to implement Hangman game using python. 27

10
Write a program to implement Tic-Tac-Toe game using python. 32

*Content beyond the University prescribed syllabi


ATTAINMENT OF PROGRAM OUTCOMES & PROGRAM SPECIFIC OUTCOMES

Program
Program
Exp. Experiments Specific
Outcomes
No. Outcomes
Attained
Attained
1 (a). Write a python program to print the multiplication
table for the given number. PO1,PO2,PO3
(b). Write a python program to check whether the PSO1
given number is prime or not.
(c) Write a python program to find factorial of the
given number.
2 Write a python program to implement simple PO1 PSO1
Chatbot.
3 (a) Write a python program to implement List
PO1,PO2 PSO1,PSO2
operations (Nested List, Length, Concatenation,
Membership, Iteration, Indexing and Slicing).
(b) Write a python program to implement List
methods (Add, Append, and Extend & Delete).

4 (a) Write a python program to Illustrate Different Set


PO1 PSO1
Operations.
(b) Write a python program to generate Calendar for
the given month and year.
(c) Write a python program to implement Simple
Calculator program
5 (a) Write a python program to Add Two Matrices.
PO1,PO2,PO3 PSO1,PSO2
(b) Write a python program to Transpose a Matrix.

6 Write a python program to implement Breadth First


PO1,PO2 PSO1
Search Traversal.

7 Write a python program to implement Water Jug PO1, PO2,


PSO1
Problem. PO4,PO5

8 (a) Write a python program to remove punctuations PO1, PO2,


PSO1,PSO2
from the given string. PO3,PO4
(b) Write a python program to sort the sentence in
alphabetical order.

9 Write a program to implement Hangman game using


PO1,PO2,PO4 PSO1
python.

10
Write a program to implement Tic-Tac-Toe game
using python. PO1,PO2 PSO1,PSO2

4
ARTIFICIAL INTELLIGENCE LAB SYLLABUS

COURSE OBJECTIVES
1. Gain a historical perspective of AI and its foundations.
2. Become familiar with basic principles of AI toward problem solving, inference,
perception, knowledge representation, and learning.
3. Investigate applications of AI techniques in intelligent agents, expert systems, artificial
neural networks and other machine learning models.
4. Experience AI development tools such as an ‘AI language’, expert system shell, and/or
data mining tool.
5. Experiment with a machine learning model for simulation and analysis.
6. Explore the current scope, potential, limitations, and implications of intelligent systems.

COURSE OUTCOMES
Student will be able to;
1. Demonstrate fundamental understanding of the history of artificial intelligence (AI) and
its foundations.
2. Apply basic principles of AI in solutions that require problem solving, inference,
perception, knowledge representation, and learning.
3. Demonstrate awareness and a fundamental understanding of various applications of AI
techniques in intelligent agents, expert systems, artificial neural networks and other
machine learning models.
4. Demonstrate proficiency developing applications in an 'AI language', expert system
shell, or data mining tool.
5. Demonstrate proficiency in applying scientific method to models of machine learning.
6. Demonstrate an ability to share in discussions of AI, its current scope and limitations,
and societal implications.

5
EXPERIMENT-1
1.1 Name of the Experiment:
a) Write a python program to print the multiplication table for given number.
1.2 OBJECTIVE: a) To write a python program to print the multiplication table for
given number.
1.3 PROGRAM:

n=int(input("Enter your table \n"))


value=int(input("Enter range of table\n"))
for i in range(1,value+1):
print(n,"*",i,"=",n*i)
output :----
Enter your table
3
Enter range of table
10
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

RESULT: Thus, the multiplication table for the given number is executed successfully and the output is verified.

1.1 Name of the Experiment:


b) Write a python program to check whether the given number is prime or not?

1.2 OBJECTIVE: To write a python program to check whether the given number is prime or not?

1.3 PROGRAM:

number=int(input("enter any number:\n"))


if number > 1:
for i in range(2,number):
if(number %i)==0:
print(number,"is not a prime number\n")
break
else:
print(number,"is a prime number\n") 6
else:
print(number,"is not a prime number\n")
output:---

Enter any number:


3
3 is a prime number

RESULT: Thus, for the given number is the program is executed successfully and the output is verified.

1.1 Name of the Experiment:


c) Write a python program to find factorial of given number.

1.2 OBJECTIVE: To write a python program to find factorial of given number.

1.3 PROGRAM:

fact=fact*i

print("Thenum=int(input("Enter a number\n"))

fact=1

if num<0:

print("factorial doesnot exist for -ve no.'s")

elif num==0:

print("The factorial of 0 is 1")

else:

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

factorial of",num,"is",fact)

output:---
Enter your number to get fatorial
5
The factorial of 5 is 120
RESULT: Thus, for the given number the factorial is executed successfully and the output is verified.

EXPERIMENT-2

2.1 Name of the Experiment: 7


a) Write a python program to implement simple Chatbot.

2.2 OBJECTIVE: To write a python program to to implement simple Chatbot.


2.3 PROGRAM:

from nltk.chat.util import Chat ,reflections

pairs=[

[r'hi',['hii']],

[r'how are you',['iam good']],

[r'where are you',['im in ogole']],

chat=Chat(pairs,reflections)

chat.converse()

Output: A simple chatbot is displayed as shown below.

>hi
hii
>how are you
iam good
>where are you
im in ongole

# Define a dictionary of predefined responses

responses = {

"hi": "Hello!",

"how are you": "I'm just a computer program, but I'm


functioning well. How can I assist you?",

"what's your name": "I'm a chatbot. You can call me


ChatBot.",

"bye": "Goodbye! Feel free to return if you have more


questions.",

# Function to get a response from the chatbot

def get_response(user_input):

user_input = user_input.lower() # Convert user input to


lowercase for case insensitivity
8

# Check if the user input matches any predefined


responses

if user_input in responses:

return responses[user_input]

else:

return "I'm sorry, I don't understand that question."

# Main loop for chatting

print("ChatBot: Hi! How can I assist you today? (Type 'bye'


to exit)")

while True:

user_input = input("You: ")

if user_input.lower() == 'bye':

print("ChatBot: Goodbye!")

break

response = get_response(user_input)

print("ChatBot:", response)

RESULT: Thus, for the chatbot program is executed successfully and the output is verified.

EXPERIMENT-3

3.1 Name of the Experiment:


(a) Write a python program to implement List operations (Nested List, Length, Concatenation, Membership,
Iteration, Indexing and Slicing).

3.2 OBJECTIVE: To write a python program to implement List operations (Nested List, Length,
Concatenation, Membership, Iteration, Indexing and Slicing).
9
3.3 PROGRAM:

L=['a','b',['cc','d',['eee','fff']],'g','h']
print(L[2])
print(L[2][2])
print(L[2][2][0])
print(L[-3])
my_list= [_ for _ in 'abcdefghi']
print("slicing",my_list[5:])
print("slicing",my_list[:4])
print(L[-3][-1])
print(L[-3][-1][-2])
print(len(L))
print(len(L[1]))
list1=[1,2,3,4]
list2=[5,6,7]
res=list1+list2
print(res)
l=[1,2,3]
print("2 contains in list",2 in l)
l=[1,2,3]
for i in range(0,len(l)):
print(l[i])
Output:--
['cc', 'd', ['eee', 'fff']]
['eee', 'fff']
eee
['cc', 'd', ['eee', 'fff']]
slicing ['f', 'g', 'h', 'i']
slicing ['a', 'b', 'c', 'd']
['eee', 'fff']
eee
5
1
[1, 2, 3, 4, 5, 6, 7]
2 contains in list True
1
2
3
RESULT: Thus, for the list operations are executed successfully and the output is
verified.
3.1 Name of the Experiment:
(b) Write a python program to implement List Methods(Add,Append and Extend &
Delete)?

3.2 OBJECTIVE: To Write a python program to implement List Methods(Add,Append and


Extend & Delete)?
10
3.3 PROGRAM:

a=[]
b=["value1","value2"]
append=input("Enter string to append")
a.append(append)
print(a)
a.extend(b)
print(a)
a.remove("value1")
print(a)

Output:--
Enter string to append 2
['2']
['2', 'value1', 'value2']
['2', 'value2']

RESULT: Thus, for the List methods are executed successfully and the output is verified .

EXPERIMENT-4
4.1 Name of the Experiment:

a) Write a python program to Illustrate Different Set Operation?

4.2 OBJECTIVE: To write a python program to Illustrate Different Set Operation?

4.3 PROGRAM:
E={0,2,4,6,8};
N={1,2,3,4,5};
print("Union of E and N is",E|N)
print("Intersection of E and N is",E&N)
print("Difference of E and N is",E-N)
print("Symmetric difference of E and N is",E^N)

Output:-

E={0,2,4,6,8};
N={1,2,3,4,5};
print("Union of E and N is",E|N)
print("Intersection of E and N is",E&N)
print("Difference of E and N is",E-N)
print("Symmetric difference of E and N is",E^N)

RESULT: Thus, the program to illustrate the set operations is executed successfully and the output is verified.
4.1 Name of the Experiment:
b) Write a python program to generate Calendar for the given month and year.

4.2OBJECTIVE: To Write a python program to generate Calendar for the given month and year.

4.3 PROGRAM: 11
import calendar
yy=int(input("Input the year:"))
mm=int(input("Input the month:"))
print(calendar.month(yy,mm))
Output:--
Input the year: 2024
Input the month: 05

May 2024

Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

RESULT: Thus, for the calendar for the given month and year is executed successfully and the output is verified.
4.1 Name of the Experiment:

c) Write a python program to implement Simple Calculator program.

4.2 OBJECTIVE: To write a python program to implement Simple Calculator program.

4.3 PROGRAM:

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
12
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): ")
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: 2
Enter second number: 5
2.0 + 5.0 = 7.0
Let's do next calculation? (Yes/no): Y
Enter choice (1/2/3/4): 2
Enter first number: 5
Enter second number: 8
5.0 - 8.0 = -3.0
Let's do next calculation? (Yes/no): Y
Enter choice (1/2/3/4): 3
Enter first number: 8
Enter second number: 5
8.0 * 5.0 = 40.0
Let's do next calculation? (Yes/no): Y
Enter choice (1/2/3/4): 4
Enter first number: 4
Enter second number: 2
4.0 / 2.0 = 2.0

RESULT: Thus, the program for the simple calculator is executed successfully and the output is verified.
EXPERIMENT-5

5.1 Name of the Experiment:

a) Write a python program to Add Two Matrices?

5.2 OBJECTIVE: Write a python program to Add Two Matrices?


13
5.3 PROGRAM:

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

Output:--

[17, 15, 4]

[10, 12, 9]

[11, 13, 18]

RESULT: Thus, the matrix addition program is executed successfully and the output is verified.
5.1 Name of the Experiment:

b)Write a python program to Transpose a Matrix?

5.2 OBJECTIVE: To write a python program to Transpose a Matrix?

5.3 PROGRAM:

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[0,0,0],
[0,0,0]]

for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)

Output:--

[12, 4, 3]
14
[7, 5, 8]

RESULT: Thus, for the transpose of the given matrix is executed successfully and the output is verified.
EXPERIMENT-6

6.1 Name of the Experiment:

Write a python program to implement Breadth First Search Traversal?

6.2 OBJECTIVE: To write a python program to implement Breadth First Search Traversal?

6.3 PROGRAM:

graph={

'5':['3','7'],

'3':['2','4'],

'7':['8'],

'2':[],

'4':['8'],

'8':[]

visited=[]

queue=[]

def bfs(visited,graph,node):

visited.append(node)

queue.append(node)

while queue:

m= queue.pop(0)

print(m,end="")

for neighbour in graph[m]:

if neighbour not in visited :

visited.append(neighbour)

queue.append(neighbour)

print("Following is the breadth First Search")

bfs(visited,graph,'5')

Output:--

Following is the breadth First Search


15
5372488

RESULT: Thus, for the BFS Search Technique is executed successfully and the output is verified.
EXPERIMENT-7
7.1 Name of the Experiment:

Write a python program to implement Water Jug Problem.

7.2 OBJECTIVE: To Write a python program to implement Water Jug Problem.

7.3 PROGRAM:

print("Water Jug Problem")


x=int(input("Enter X:\n"))
y=int(input("Enter Y:\n"))
while True:
rno=int(input("Enter the Rule No\n"))
if rno==1:
if x<4:
x=4

if rno==2:
if y<3:
y=3

if rno==5:
if x>0:
x=0

if rno==6:
if y>0:
y=0

if rno==7:
if x+y>= 4 and y>0:
x,y=4,y-(4-x)

if rno==8:
if x+y>=3 and x>0:
x,y=x-(3-y),3

if rno==9:
if x+y<=4 and y>0:
x,y=x+y,0

if rno==10:
if x+y<=3 and x>0:
x,y=0,x+y
print("X =",x)
print("Y =",y)
if (x==2):
print(" The result is a Goal state")
break

Output:--

Water Jug Problem


Enter X:
16
0
Enter Y:
0
Enter the Rule No
2
X=0
Y=3
Enter the Rule No
9
X=3
Y=0
Enter the Rule No
2
X=3
Y=3
Enter the Rule No
7
X=4
Y=2
Enter the Rule No
5
X=0
Y=2
Enter the Rule No
9
X=2
Y=0
The result is a Goal state

RESULT: Thus, the water jug problem is executed successfully and the output is verified.

EXPERIMENT-8

8.1 Name of the Experiment:


a)Write a python program to remove punctuations from the given string.

8.2 OBJECTIVE: To write a python program to remove punctuations from the given string.
.

8.3 PROGRAM:

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Heyyah!!!, My name is Sam ;)."
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

print(no_punct)

Output:--

Heyyah My name is Sam

RESULT: Thus, the program to remove punctuations is executed


17 successfully and the output is verified.
8.1 Name of the Experiment:
b) Write a python program to sort the sentence in alphabetical order?
8.2 OBJECTIVE: To write a python program to sort the sentence in alphabetical order?

8.3 PROGRAM:

my_str = "Hello My name is Sam"

words = [word.lower() for word in my_str.split()]

words.sort()

print("The sorted words are:")

for word in words:

print(word)

Output:--

The sorted words are:


hello
is
my
name
sam

RESULT: Thus, the program to sort the sentence in alphabetical order is executed successfully and the output is
verified.

EXPERIMENT-9

9.1 Name of the Experiment:


a) Write a python program to implement Hangman game using python.

9.2 OBJECTIVE: To write a python program to implement Hangman game using python.
.

9.3 PROGRAM:

#importing the time module

import time

#welcoming the user

name = input("What is your name? ")

print ("Hello, " + name, "Time to play hangman!")

#wait for 1 second

time.sleep(1)

print ("Start guessing...")

time.sleep(0.5)

#here we set the secret. You can select any word to play with. 18

word = ("secret")
#creates an variable with an empty value

guesses = ''

#determine the number of turns

turns = 10

# Create a while loop

#check if the turns are more than zero

while turns > 0:

# make a counter that starts with zero

failed = 0

# for every character in secret_word

for char in word:

# see if the character is in the players guess

if char in guesses:

# print then out the character

print (char,end=""),

else:

# if not found, print a dash

print ("_",end=""),

# and increase the failed counter with one

failed += 1

# if failed is equal to zero

# print You Won

if failed == 0:

print ("You won")

# exit the script

break

# ask the user go guess a character

guess = input("guess a character:")

# set the players guess to guesses


19
guesses += guess

# if the guess is not found in the secret word


if guess not in word:

# turns counter decreases with 1 (now 9)

turns -= 1

# print wrong

print ("Wrong")

# how many turns are left

print ("You have", + turns, 'more guesses' )

# if the turns are equal to zero

if turns == 0:

# print "You Lose"

print ("You Lose" )

Output:

What is your name? wesley

Hello, Wesley Time to play hangman!

Start guessing...

______guess a character:s

s_____guess a character:r

s__r__guess a character:t

s__r_tguess a character:e

se_retguess a character:c

secretYou won

RESULT: Thus, the program to implement Hangman Game is executed successfully and the output is verified.

EXPERIMENT-10

10.1 Name of the Experiment:


Write a python program to implement Tic-Tac-Toe game using python.

10.2 OBJECTIVE: Write a python program to implement Tic-Tac-Toe game using python.

10.3 PROGRAM:
20
import random

board = ["-", "-", "-",


"-", "-", "-",

"-", "-", "-"]

currentPlayer = "X"

winner = None

gameRunning = True

# game board

def printBoard(board):

print(board[0] + " | " + board[1] + " | " + board[2])

print("---------")

print(board[3] + " | " + board[4] + " | " + board[5])

print("---------")

print(board[6] + " | " + board[7] + " | " + board[8])

# take player input

def playerInput(board):

inp = int(input("Select a spot 1-9: "))

if board[inp-1] == "-":

board[inp-1] = currentPlayer

else:

print("Oops player is already at that spot.")

# check for win or tie

def checkHorizontle(board):

global winner

if board[0] == board[1] == board[2] and board[0] != "-":

winner = board[0]

return True

elif board[3] == board[4] == board[5] and board[3] != "-":


21
winner = board[3]

return True
elif board[6] == board[7] == board[8] and board[6] != "-":

winner = board[6]

return True

def checkRow(board):

global winner

if board[0] == board[3] == board[6] and board[0] != "-":

winner = board[0]

return True

elif board[1] == board[4] == board[7] and board[1] != "-":

winner = board[1]

return True

elif board[2] == board[5] == board[8] and board[2] != "-":

winner = board[3]

return True

def checkDiag(board):

global winner

if board[0] == board[4] == board[8] and board[0] != "-":

winner = board[0]

return True

elif board[2] == board[4] == board[6] and board[4] != "-":

winner = board[2]

return True

def checkIfWin(board):

global gameRunning

if checkHorizontle(board):

printBoard(board)
22
print(f"The winner is {winner}!")

gameRunning = False
elif checkRow(board):

printBoard(board)

print(f"The winner is {winner}!")

gameRunning = False

elif checkDiag(board):

printBoard(board)

print(f"The winner is {winner}!")

gameRunning = False

def checkIfTie(board):

global gameRunning

if "-" not in board:

printBoard(board)

print("It is a tie!")

gameRunning = False

# switch player

def switchPlayer():

global currentPlayer

if currentPlayer == "X":

currentPlayer = "O"

else:

currentPlayer = "X"

def computer(board):

while currentPlayer == "O":

position = random.randint(0, 8)

if board[position] == "-":

board[position] = "O"
23
switchPlayer()

while gameRunning:
printBoard(board)

playerInput(board)

checkIfWin(board)

checkIfTie(board)

switchPlayer()

computer(board)

checkIfWin(board)

checkIfTie(board)

Output:

-|-|-

---------

-|-|-

---------

-|-|-

Select a spot 1-9: 7

-|O|-

---------

-|-|-

---------

X|-|-

Select a spot 1-9: 5

O|O|-

---------

-|X|-

---------

X|-|-
24
Select a spot 1-9: 8

O|O|-
---------

-|X|O

---------

X|X|-

Select a spot 1-9: 9

O|O|-

---------

-|X|O

---------

X|X|X

The winner is X!

O|O|-

---------

O|X|O

---------

X|X|X

The winner is X!

RESULT: Thus, the program to implement Tic-Tac Toe game is executed successfully and the output is verified.

25

You might also like