Chapter -14 (Object Oriented Programming)
For learn how to download and install python link here: How to download and install python in window
For learn how to run and execute the code in python link here:How to write and run the code
In this blog, the format is first I write Code then Result of that code. You can directly copy the code and so your time save in written that code. Also , image of the code and result and after which it contain explanation of the code.
Example-1: Write a program by use of class and add any two value.
Code:
class Example:
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a + self.b
e=Example(8,6)
print(e.add())
Result:
14
Explanation:-
- 1st step we make a class and give some name to it, in this example we give name 'Example'. Remember class name start with capital letter.
- 2nd step is we must include __init__ function,these underscore called constructor and these use to create object from your class. If you make function without using these underscore and init function then it show error.
- 3rd step first argument in constructor is self and after we give variable name.
- Self is used to distinguish your class's variable and method.
- 4th step To use the object’s methods, use the dot operator, as here we use e.add()
- Here in this example, In 3rd line use self.a= and self.b=b to distinguish class variable.
- After all these thing we use def command and then you give any name here but I give 'add' and then write self in bracket this is compulsory in every code where you use class otherwise show error.
- After we give command that add the a and b value
- In last we write 'e' you can use any word instead of e and then e is equal to the name which you use in class i.e., Example
- As you see, Above we write def __init__(self,a,b), so here in last of code we should give the value of a and b, so give value 8 and 6.
- Then in last of code, we first make class value as e=Example(8,6) and then we use def command i.e, add so it become print(e.add()) and it give the answer.
- Don't worry if you not understand we have more example also.
- Here you think, Why we this complex instead of use can use a=8 and b=6 and then give command print(a+b) and it also give the same answer.
- But these class(object oriented programming) use when we design software. You may give task of written one type of code and you partner give task to write another type of code and at last we can combine all these thing without get any other result. So, here is the basic for easy understand.
Example-2: Write a program with a class name Analyzer and find the len of word, word start with 't' and find the number of word whose length is 2.
Code:
from string import punctuation
class Analyzer:
def __init__(self,s):
for c in punctuation:
s=s.replace(c,'')
s=s.lower()
self.words=s.split()
def number_of_words(self):
return len(self.words)
def starts_with(self,s):
return len([w for w in self.words if w[:len(s)]==s])
def number_with_length(self,n):
return len([w for w in self.words if len(w)==n])
s='This is a test of the class.'
analyzer=Analyzer(s)
print(analyzer.words)
print('Number of words:', analyzer.number_of_words())
print('Number of words starting with "t":',analyzer.starts_with('t'))
print('Number of 2-letter words:', analyzer.number_with_length(2))
Result:
['this', 'is', 'a', 'test', 'of', 'the', 'class']
Number of words: 7
Number of words starting with "t": 3
Number of 2-letter words: 2
Explanation:-
- This code you see previously, if you read my blog. I describe about this in chapter-6 (string)
- So first of all we call the import punctuation by-- from string import punctuation
- Then use add class and the first letter of class is capital so use give class name Analyzer
- Then it is important to use __init__() and in this bracket 1st name should be self and then we can any name or value according to our choice.
- In the previous example we give two value like a and b, but here we give only one 's', because it depend upon situation. If you need two variable then you use two if need one then use only one variable.
- Then we use, for c in punctuation:- to check every letter and found punctuation
- After we replace the punctuation with ('' -- double quotes) it means without space and if give space between two quotes (' ') then it replace the punctuation by one space.
- Then we make all letter in small letter (not capital letter) and then we split this to make the string into list.
- Question: Why we first use this as string and then convert into list.
- Answer: Because list have no command 'replace' so we cannot able to replace punctuation in list.
- After that string form as you can see in result. Now we use def function give name according to our own choice.
- 1st we give number_of_words(self), you can choose any name instead of this and then we give in next line command for calculate that we want to find the length of list so we use len(self.words), we use self.words because the name of the list is self.words.
- 2nd we give name:- starts_with(self,s)
- Question: In above function you use only self, but here why self and s?
- Answer: In above function we want only to calculate the length of list, but here we want to find word which may start from any letter, here ''s'' act as variable. If you see in last of code we use analyzer.starts_with('t') it means we want to find the word which start with 't', you can replace 't' and can use any letter which you want to found.
- 3rd we give name:- number_with_length(self,n)
- Similarly as above here 'n' act as variable
- In next line we use len([w for w in self.words if len(w)==n]) :- It means find the letter which start with 2 or 3 or 4 or any number which you write in the last of code. If you see in last we use analyzer.number_with_length(2):- here we use 2 it means find length of all word which length is 2 and here result is also 2. As you check in list i.e., is and of are only two word which are of 2 letter.
- In last we write the string: 'This is a test of the class'
- In Previous Example 1:- we use e=Example(8,6) but here we use analyzer you can use any name instead of analyzer. Remember class name Analyzer and this analyzer=Analyzer.words is different. Because class name start with capital and here it start with small letter(analyzer).
- In previous example -1:- we use e.add(), it states that e=class name i.e, 'Example' and variable in bracket (8,6) , & def function name is 'add' so we combine e.add() .
- But here in this example we use analyzer.number_of_words() it states that class name is Analyzer and variable is 's' & def function name is number_of_words so after combine we use analyzer.number_of_word(), similarly so on.
- Hope this time you better understand then previous example.
Example-3: This is the Basic example to explain the inheritance. In inheritance you take the data of one class into other class.
Code:
class Parent:
def __init__(self,a):
self.a=a
def method1(self):
print(self.a*2)
def method2(self):
print(self.a+'!!!')
class Child(Parent):
def __init__(self,a,b):
self.a=a
self.b=b
def method3(self):
print(self.a*7)
def method4(self):
print(self.a + self.b)
p=Parent('hi')
c=Child('hello','bye')
print('Parent method 1:'), p.method1()
print('Parent method 2:'), p.method2()
print('Child method3:'), c.method3()
print('Child method4'), c.method2()
print('Child method 2:'), c.method2()
print('Child method 1:'), c.method1()
Result:
Parent method 1:
hihi
Parent method 2:
hi!!!
Child method3:
hellohellohellohellohellohellohello
Child method4
hello!!!
Child method 2:
hello!!!
Child method 1:
hellohello
Explanation:-
- First of all we make class and give it name, in this case use 'Parent'. Then same use __init__ command and then use self and variable in bracket. Here variable is 'a'. Then we use self.a=a
- Then use def function and here name we give method1 and in bracket give only 'self', because we not want any variable and in result we want self.a*2 (self.a*2 means anything you give name to variable 'a' is written twice in output.)
- Then we use another def function and here give name method2 and in bracket we use only 'self', because we not want to add any variable and in result we want self.a+'!!!' (means self.a is the value of a and in last of this value it add three exclamatory sign)
- This example is easy upto now, because we read it previously but here a new complex thing , we make another class 'Child' and in this class Child we call the above class i.e., Parent.
- To call class in another class simply in bracket give the name of class which you want to call. Here , we use class Child(Parent), It means we call Parent class in Child class.
- Now in class Child we use def __init__ and then in bracket we use self, and two variable i.e., a and b.
- In class Child, we use def function, these are method3 and method 4. In method3 in result we use self.a*7, it means 'a' repeat 7 times and here 'a' is hello so it repeat 7 times.
- In method4 we use self.a+ self.b and here a='hello' and b='bye' and in this appear hellobye in result.
- But now next two line are different here we use c.method2().
- Question:- In Child class their is no method2, but it give result in output. Why?
- Answer:- Because method2 in Parent class and we call Parent class in Child so here method2 give result as parent class , but here it take variable as 'hello' not 'hi'.
- In next line c.method1() , but Child class not contain c.method1() so it call from parent class, give result as the parent but variable is from child class.
Example-4: Another example of inheritance. In this example we make a class Parent and then we inherit this class in another class name Child.
Code:
class Parent:
def __init__(self,a):
self.a=a
def hello(self):
print('hello how are you')
class Child(Parent):
def __init__(self,a,b):
self.a=a
self.b=b
def print_var(self):
Parent.hello(self)
print(self.b)
a1=Child('Hello','hi')
a1.print_var()
Result:
hello how are you
hi
Explanation:-
- First of all we make a class and here we give name as Parent.
- Then we use __init__ and in bracket use self and variable i.e., 'a'.
- Then we make 'hello' def function and in output we give command 'hello how are you'
- Again we make a class called Child and in bracket of the child class we call Parent class.
- Then we again use __init__ and now give two variable in this.
- Then we make print_var def function and in output we give command Parent.hello(self) and print(self.b). Here, Parent.hello(self) means class name.def function name(self) as you see before in example-1 i.e., e.add(), same as example 1. Only difference is in example-1 we give e=Example(8,6) and here we directly write name of class and then use dot and then def function name.
- print(self.b) give the result according to value of 'b' which we use in child class.
- In output we use a1=Child('Hello','hi') , Here a='Hello' and b='Hi'.
- Then we use a1.print_var() it means whatever in output of print_var it give result. Under print_var two output i.e, Parent.hello(self) and print(self.b)
- So, Parent.hello(self) give output hello how are you and print(self.b) give output hi
Example-5:- Write a program and ask user first name , last name and age and in output print : Hello my name is: User first name + last name + age.
Code:
class Person(object):
def __init__(self, first_name, last_name, age):
self.first_name=first_name
self.last_name=last_name
self.age=age
self.full_name=first_name +" " + last_name+' and my age is '+self.age
def greet(self):
print('Hello, my name is ' +self.full_name+ ".")
bob=Person('Hello','World','30')
bob.greet()
Result:
Hello, my name is Hello World and my age is 30.
Explanation:-
- First of all we make a class , and give name Person.
- Then we make __init__ and then make bracket, it contain self and then 3 variable i.e., first_name, last_name, age.
- Then we use def function and give name 'greet' and here no variable.
- Then we give command self.full_name and self.full_name contain first name + last name+ age
- Then we give name bob you can give any name instead of this and now bob equal to class name i.e., Person and then in bracket contain three varible i.e., firstname, lastname, age.
- Finally bob.def function name ie., greet and i.e., bob.greet() give result.
Example-6:- Write a program of Card game, in which if user write number 11 then it write Jack , if write 12 then Queen, if 13 then King , if 14 then Ace. If user write user less than 10 then print only number .
eg. If user write 11 of Diamond then it print 'Jack of Diamond' and
If user write 4 of Heart then it print '4 of Heart'
Code:
class Card:
def __init__(self,value,suit):
self.value=value
self.suit=suit
def cardvalue(self):
names=['Jack','Queen','King','Ace']
if self.value<=10:
return '{} of {}'.format(self.value, self.suit)
else:
return '{} of {}'.format(names[self.value-11],self.suit)
a1=Card(11,'Diamond')
a2=Card(4,'Heart')
print(a1.cardvalue())
print(a2.cardvalue())
Result:
Jack of Diamond
4 of Heart
Explanation:-
- Here first we make a class name card and then similar __init__ and then in bracket add self & two variable ie. value and suit.
- Now in another def function name as cardvalue and then in output use names=['Jack','Queen','King','Ace'].
- As you see above in def __init__ in bracket, first we use value and then suit. and in output as you see below a1=Card(11,'Diamond'), so here 11 is value and Diamond is suit.
- So, in def cardvalue when we write if self.value<10 it mean if value less than or equal to 10 then it print Value as it is.
- If value greater than 10, example if value is 11 then in output 'Jack' as you see in cards (list) first word is Jack and if you write 12 then output is 'Queen' same if 13 then 'King' and in 14 then 'Ace' it print because '{} of {}'.format(names[self.value-11], self.suit)
| |
\/ \/
Value-11 'Diamond','Heart'
- In output you see a1=Card(value, suit)
| |
| |
\/ \/
11 Diamond
a2=Card(value,suit)
| |
| |
\/ \/
4 Heart
- In output you see a1 . cardvalue()
| |
| |
\/ \/
Class Def function
name name
Example-7:- Write a class Card_group with fields called nextcard,hasCard, size.
cards=[10,4,-1,5,-2,19,87,45]
Then nextcard return the value of first card present in cards list, hasCard return whether cards list greater than 0 or not, size return the length of cardslist.
Code:
class Card_group:
def __init__(self,cards=[]):
self.cards=cards
def nextCard(self):
return self.cards.pop(0)
def hasCards(self):
return len(self.cards)>0
def size(self):
return len(self.cards)
cards=[10,4,-1,5,-2,19,87,45]
a=Card_group(cards)
print(a.nextCard())
print(a.hasCards())
print(a.size())
Result:
- First we make a class and name it Card_group.
- Then next step is __init__ and then add variable in bracket.
- Here variable is cards=[], this cards value we can choose as you see in question card value is cards=[10,4,-1.......].
- Then three def function: we use nextCard, hasCard and size.
| | |
| | |
\/ \/ \/
In this output here use here use
we use pop(0) len(self.cards)>0 len(self.cards)
- Then in pop(0), here 0 means at position 1 in list i.e. 10
- In len(self.cards)>0 , so here it not ask the length of card but it ask its length >0 , ofcourse length >0 so it write true in answer.
- In next use len(self.cards) now it ask length of list and it print the answer i.e. 7
Example-8:- Same question as Example-7 ,except make another class with name Standard_deck and in this make cards group like 'Heart,1', 'Heart ,2', ........., to 'Heart,13',
'Diamond,1','Diamond,2',............, to 'Diamond,13',
Clubs,1','Clubs,2',......., to 'Clubs',13',
'Spades,1, 'Spades,2'....... to 'Spades,13'
Code:
class Card_group:
def __init__(self,cards=[]):
self.cards=cards
def nextCard(self):
return self.cards.pop(0)
def hasCards(self):
return len(self.cards)>0
def size(self):
return len(self.cards)
class Standard_deck(Card_group):
def Cards(self):
cards=[]
for s in ['Heart','Diamond','Clubs','Spades']:
for v in range(1,14):
cards.append((s,v))
print(cards)
cards=[10,4,-1,5,-2,19,87,45]
a=Card_group(cards)
print(a.nextCard())
print(a.hasCards())
print(a.size())
b=Standard_deck()
b.Cards()
Result:
10
True
7
[('Heart', 1), ('Heart', 2), ('Heart', 3), ('Heart', 4), ('Heart', 5), ('Heart', 6), ('Heart', 7), ('Heart', 8), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13)]
[('Heart', 1), ('Heart', 2), ('Heart', 3), ('Heart', 4), ('Heart', 5), ('Heart', 6), ('Heart', 7), ('Heart', 8), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Diamond', 1), ('Diamond', 2), ('Diamond', 3), ('Diamond', 4), ('Diamond', 5), ('Diamond', 6), ('Diamond', 7), ('Diamond', 8), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13)]
[('Heart', 1), ('Heart', 2), ('Heart', 3), ('Heart', 4), ('Heart', 5), ('Heart', 6), ('Heart', 7), ('Heart', 8), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Diamond', 1), ('Diamond', 2), ('Diamond', 3), ('Diamond', 4), ('Diamond', 5), ('Diamond', 6), ('Diamond', 7), ('Diamond', 8), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13), ('Clubs', 1), ('Clubs', 2), ('Clubs', 3), ('Clubs', 4), ('Clubs', 5), ('Clubs', 6), ('Clubs', 7), ('Clubs', 8), ('Clubs', 9), ('Clubs', 10), ('Clubs', 11), ('Clubs', 12), ('Clubs', 13)]
[('Heart', 1), ('Heart', 2), ('Heart', 3), ('Heart', 4), ('Heart', 5), ('Heart', 6), ('Heart', 7), ('Heart', 8), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Diamond', 1), ('Diamond', 2), ('Diamond', 3), ('Diamond', 4), ('Diamond', 5), ('Diamond', 6), ('Diamond', 7), ('Diamond', 8), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13), ('Clubs', 1), ('Clubs', 2), ('Clubs', 3), ('Clubs', 4), ('Clubs', 5), ('Clubs', 6), ('Clubs', 7), ('Clubs', 8), ('Clubs', 9), ('Clubs', 10), ('Clubs', 11), ('Clubs', 12), ('Clubs', 13), ('Spades', 1), ('Spades', 2), ('Spades', 3), ('Spades', 4), ('Spades', 5), ('Spades', 6), ('Spades', 7), ('Spades', 8), ('Spades', 9), ('Spades', 10), ('Spades', 11), ('Spades', 12), ('Spades', 13)]
Explanation:-
- This example is same as previous example except here use one more class name Standard_deck and in this class, we call upper class by place name in bracket. i.e., Standard_deck(Card_group)
- Now in this you no need for use __init__, because you don't want to give add variable. Also, you already call Card_group class in this standard_deck class & Card_group class have __init__ so it take data from that class. So, that's why in this case it not show error.
- Then we use def Cards and here we create empty list with name of cards=[] and then we use 2 loop one for value and other for suit of card and then we use append the list. Now, data of these 2 loop add in this empty list and it appear in output.
Example-9:- Same as Example-8, except we done a single change, Here in this example we remove cards=[] after def Cards(self): , then we see the change.
Code:
class Card_group:
def __init__(self,cards=[]):
self.cards=cards
def nextCard(self):
return self.cards.pop(0)
def hasCards(self):
return len(self.cards)>0
def size(self):
return len(self.cards)
class Standard_deck(Card_group):
def Cards(self):
for s in ['Heart','Diamond','Clubs','Spades']:
for v in range(1,14):
cards.append((s,v))
print(cards)
cards=[10,4,-1,5,-2,19,87,45]
a=Card_group(cards)
print(a.nextCard())
print(a.hasCards())
print(a.size())
b=Standard_deck()
b.Cards()
Result:
10
True
7
[4, -1, 5, -2, 19, 87, 45, ('Heart', 1), ('Heart', 2), ('Heart', 3), ('Heart', 4), ('Heart', 5), ('Heart', 6), ('Heart', 7), ('Heart', 8), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Diamond', 1), ('Diamond', 2), ('Diamond', 3), ('Diamond', 4), ('Diamond', 5), ('Diamond', 6), ('Diamond', 7), ('Diamond', 8), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13), ('Clubs', 1), ('Clubs', 2), ('Clubs', 3), ('Clubs', 4), ('Clubs', 5), ('Clubs', 6), ('Clubs', 7), ('Clubs', 8), ('Clubs', 9), ('Clubs', 10), ('Clubs', 11), ('Clubs', 12), ('Clubs', 13), ('Spades', 1), ('Spades', 2), ('Spades', 3), ('Spades', 4), ('Spades', 5), ('Spades', 6), ('Spades', 7), ('Spades', 8), ('Spades', 9), ('Spades', 10), ('Spades', 11), ('Spades', 12), ('Spades', 13)]
Explanation:-
- As you see previous example their is no big difference in this example and previous example. Only that in previous example, in result you only see card suit with their value.
- But in this example you see cards=[10,4,-1.......] also in result. This is because we not create separate list below def Cards, so it take data from Card_group class and in output print combination of both.
Example-10:- Write a program and include previous example code, but also include pinochle deck class and print the pinochle card. A Pinochle deck has only nines, tens, jacks, queens, kings, and aces. There are two copies of each card in each suit.
Code:
class Card_group:
def __init__(self,cards=[]):
self.cards=cards
def nextCard(self):
return self.cards.pop(0)
def hasCards(self):
return len(self.cards)>0
def size(self):
return len(self.cards)
class Standard_deck(Card_group):
def Cards(self):
cards=[]
for s in ['Heart','Diamond','Clubs','Spades']:
for v in range(1,14):
cards.append((s,v))
print(cards)
class Pinochle_deck(Card_group):
def pinochle(self):
cards=[]
for s in ['Heart','Diamond','Clubs','Spades']*2:
for v in range(9,15):
cards.append((s,v))
print(cards)
cards=[10,4,-1,5,-2,19,87,45]
a=Card_group(cards)
print(a.nextCard())
print(a.hasCards())
print(a.size())
b=Standard_deck()
b.Cards()
c=Pinochle_deck()
c.pinochle()
Result:
10
True
7
[('Heart', 1), ('Heart', 2), ('Heart', 3), ('Heart', 4), ('Heart', 5), ('Heart', 6), ('Heart', 7), ('Heart', 8), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Diamond', 1), ('Diamond', 2), ('Diamond', 3), ('Diamond', 4), ('Diamond', 5), ('Diamond', 6), ('Diamond', 7), ('Diamond', 8), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13), ('Clubs', 1), ('Clubs', 2), ('Clubs', 3), ('Clubs', 4), ('Clubs', 5), ('Clubs', 6), ('Clubs', 7), ('Clubs', 8), ('Clubs', 9), ('Clubs', 10), ('Clubs', 11), ('Clubs', 12), ('Clubs', 13), ('Spades', 1), ('Spades', 2), ('Spades', 3), ('Spades', 4), ('Spades', 5), ('Spades', 6), ('Spades', 7), ('Spades', 8), ('Spades', 9), ('Spades', 10), ('Spades', 11), ('Spades', 12), ('Spades', 13)]
[('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Heart', 14), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13), ('Diamond', 14), ('Clubs', 9), ('Clubs', 10), ('Clubs', 11), ('Clubs', 12), ('Clubs', 13), ('Clubs', 14), ('Spades', 9), ('Spades', 10), ('Spades', 11), ('Spades', 12), ('Spades', 13), ('Spades', 14), ('Heart', 9), ('Heart', 10), ('Heart', 11), ('Heart', 12), ('Heart', 13), ('Heart', 14), ('Diamond', 9), ('Diamond', 10), ('Diamond', 11), ('Diamond', 12), ('Diamond', 13), ('Diamond', 14), ('Clubs', 9), ('Clubs', 10), ('Clubs', 11), ('Clubs', 12), ('Clubs', 13), ('Clubs', 14), ('Spades', 9), ('Spades', 10), ('Spades', 11), ('Spades', 12), ('Spades', 13), ('Spades', 14)]
Explanation:-
- This example is same as previous example except here we add one more class name as Pinochle_deck and in this we take data from 1st class--Card_group. So, we don't need to add constructor here.So, we directly made pinochle def function.
- In this Pinochle_deck class, we do some change we double the suit but value take from range 9 to 15. so this called Pinochle card.
- In output of c=Pinochle_deck() and then c.pinochle(), when we write by their combination it become c.pinochle()
Example-11:- Write a program for tic tac toe game.
Code:
def tic_tac_toe():
# First of all create a string from 1 to 9 number
l='|_1_|_2_|_3_|\n|_4_|_5_|_6_|\n|_7_|_8_|_9_|'
print(l)
count1=0
count2=0
# Here we give range upto 4 beacuase in 8 turn match over and last digit not play role
for i in range(4):
p1=eval(input('Enter you position at which you want X:'))
# Here we check whether the number present in list: 1 or not
# If not present it means this number already occupy and loop break
if str(p1) in l:
print('Now O turn')
else:
print('This position already occupy,retry')
break
# Here we replace the integer with letter
l=l.replace(str(p1),'X')
print(l)
# If condition match then it count it as 1 and if count1=1 then X won and the loop break
if l[2]=='X' and l[6]=='X'and l[10]=='X' or l[16]=='X'and l[20]=='X'and l[24]=='X' or\
l[30]=='X' and l[34]=='X'and l[38]=='X' or l[2]=='X'and l[16]=='X'and l[30]=='X' or\
l[6]=='X' and l[20]=='X'and l[34]=='X' or l[10]=='X'and l[24]=='X'and l[38]=='X' or\
l[2]=='X' and l[20]=='X'and l[38]=='X' or l[20]=='X'and l[20]=='X'and l[30]=='X':
count1=count1+1
if count1>=1:
print('X won')
break
# Same as above we take player 2 input and check whether that number present or not.
# If not present it means already occupy and loop break
p2=eval(input('Enter your position at which you want O:'))
if str(p2) in l:
print('Now X turn')
else:
print('This position already occupy, retry')
break
l=l.replace(str(p2),'O')
print(l)
# If condition match then it count it as 1 and if count2=1 then O won and the loop break
if l[2]=='O' and l[6]=='O'and l[10]=='O' or l[16]=='O' and l[20]=='O'and l[24]=='O' or\
l[30]=='O' and l[34]=='O'and l[38]=='O' or l[2]=='O' and l[16]=='O'and l[30]=='O' or\
l[6]=='O' and l[20]=='O'and l[34]=='O' or l[10]=='O' and l[24]=='O'and l[38]=='O' or\
l[2]=='O' and l[20]=='O'and l[38]=='O' or l[20]=='O' and l[20]=='O'and l[30]=='O':
count2=count2+1
if count2>=1:
print('O won')
break
# If above all condition not satisfy it means match tie
if count1==count2:
print('match tie')
tic_tac_toe()
Result:
|_1_|_2_|_3_|
|_4_|_5_|_6_|
|_7_|_8_|_9_|
Enter you position at which you want X:1
Now O turn
|_X_|_2_|_3_|
|_4_|_5_|_6_|
|_7_|_8_|_9_|
Enter your position at which you want O:2
Now X turn
|_X_|_O_|_3_|
|_4_|_5_|_6_|
|_7_|_8_|_9_|
Enter you position at which you want X:3
Now O turn
|_X_|_O_|_X_|
|_4_|_5_|_6_|
|_7_|_8_|_9_|
Enter your position at which you want O:4
Now X turn
|_X_|_O_|_X_|
|_O_|_5_|_6_|
|_7_|_8_|_9_|
Enter you position at which you want X:5
Now O turn
|_X_|_O_|_X_|
|_O_|_X_|_6_|
|_7_|_8_|_9_|
Enter your position at which you want O:6
Now X turn
|_X_|_O_|_X_|
|_O_|_X_|_O_|
|_7_|_8_|_9_|
Enter you position at which you want X:7
Now O turn
|_X_|_O_|_X_|
|_O_|_X_|_O_|
|_X_|_8_|_9_|
X won
Explanation:-
This example explain in the code so see the image of code.
No comments:
Post a Comment
If you have any doubt, let me know.