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

Python Learning Documentation

Python arrays allow storing multiple values in a single variable. Some key points: - Numerical, string, and float arrays can be created to store different data types. - Individual array values can be accessed using their index number. - Arrays can be modified by updating existing values or adding/removing elements. The append() and extend() methods add new values, while remove() deletes elements. - Various array methods allow printing, modifying, and manipulating array data in Python programs.

Uploaded by

Vivek Karthik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Python Learning Documentation

Python arrays allow storing multiple values in a single variable. Some key points: - Numerical, string, and float arrays can be created to store different data types. - Individual array values can be accessed using their index number. - Arrays can be modified by updating existing values or adding/removing elements. The append() and extend() methods add new values, while remove() deletes elements. - Various array methods allow printing, modifying, and manipulating array data in Python programs.

Uploaded by

Vivek Karthik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Python

Hello World
Python is a very fun and simple language, it also has a very straightforward syntax (which is
always a good thing!)

We are going to start by creating a new file, we are going to name this file helloworld.py
Every python file will end with the extension of .py (there are more of them, but for this course
we don’t need to worry about those)

The simplest directive in Python is the "print" directive - it simply prints out a line (and also
includes a new line, unlike in C).

There are two main versions in Python (and there are big differences between them) python 2
and python 3. One difference between Python 2 and 3 is the print statement.

In Python 2, the "print" statement is not a function, and therefore it is invoked without
parentheses.
However, in Python 3, it is a function, and must be invoked with parentheses.

print("Hello World!")

The print statement does exactly what its name says, it prints whatever you give to it.
Lets test it, write in your terminal after saving the file python helloworld.py

Lets see some more examples:


It can print strings
print("A string")

It can print numbers


print(2)

Python also has the ability to do simple math calculations


Some examples:

print(1+2) This should give us 3


print(5+5) This should give us 10
print(8*6) This should give us 48
print(25/4) This should give us 6
This is just basic math, but there is a lot more, Python is so powerful that you can do almost
everything with it!
You should be very careful when you work with integers and strings. There is a very big
difference between them

print("1") This will print a string, so you can not do any math calculations with it
print("1" + 1) If you try anything like this, you will always receive an error.
Reason being, you can't just add an string and an integer together. It has to be of same
datatype.

So far we've seen how to print a statement, how to do some math and we also seen what errors
we might encounter when we have bad syntax.

Variables
Create a new file called variables.py
Short and simple, A variable is just a box that you can put stuff in. You can use variables to
store all kinds of stuff

So let’s work with some strings and numbers once again, but this time, we will use variables

numberOne = 5
numberTwo = 5
print(numberOne + numberTwo)

You might wonder "why don't we just do that math calculation without variables"
Well, you see... later on you might want to use variables in order to store data, and that data be
used again for another purpose

Run the file and see if it works


With python variables.py

Let’s see how it would work with strings


greeting = "Hello there"
name = "John Doe"
print(greeting + ' ' + name)
As you can see, we are adding an empty string between the two variables, that is because it
wouldn't have space if we just print it without that.
You can also add some space in one of the variables, it’s whatever you prefer

Run the file and see if it works


With python variables.py
String methods - formating
Create a new file called stringformating.py
Now that we covered integers, strings and variables, it’s time to go into something more
advanced, string formatting.
String formating is quite a fun thing, simply put: there are a lot of methods made for strings that
can be used, from capitalizing to split and replace and…. there are a lot!
But right now we will concentrate on .format, which is quite widely used!

Alright, let’s create a simple program that will insert age and name.
age = 26
name = "John Doe"

"No, no, no! You told us that strings and integers do not work together."
Well, they do not. but there is a way to overcome that. Let’s see:

print("My age is " + str(age) + " years")

This str(age) transforms the data from the variable age (which, obviously, has an integer) to a
string.
Test it yourself, run the file and see if it works

Let’s continue with our little program.


print("My name is {0}, I am {1} years old".format(name, age))

You might wonder what those curly braces/brackets are for, well those are replacements fields.
Basically, 0 is the first one and 1 is the second one (and it keeps going as you add them)
and this way you do not need to add the data yourself, you add them in the format function and
it all takes care by itself.

Run the file and see how it looks.

Let’s work with some more formatting


print("""How many days are in each month::
January - {2}
February - {0}
March - {2}
April - {1}
May - {2}
June - {1}
July - {2}
August - {2}
September - {1}
October - {2}
November - {1}
December - {2}""".format(28, 30, 31))
This will create put the number of days every month has, run the file and see if it works

More string formatting


We can play in multiple ways with our strings.

Let’s say that we want our string to be on multiple lanes, how would we do that?
We can use the keyword \n

splitString = "This string has been\nsplit over\nseveral\nlines"


print(splitString)

We can also use the command \t to tab the string


tabbedString = "a\t b\t c\t d\t"
print(tabbedString)

Let’s say that we want to have a quote inside a string. if you write it like this
print("Here is a quote "Quote" ")
This will fail. What you can do is either have two apostrophes or only one. Like this:
print('Example one:"I would take the awe of understanding over the awe of ignorance any day."')

print("Example two:'That which can be asserted without evidence, can be dismissed without
evidence'")

But what if you have apostrophes for example: I'd. Then the syntax would have an error.. in that
case we can do this:
print('''”Example three: "I'd take the awe of understanding over the awe of ignorance any
day."”””)

print("""Example four:
Customer: 'Not much of a cheese shop really, is it?'
Shopkeeper: 'Finest in the district, sir.'
Customer: 'And what leads you to that conclusion?'
Shopkeeper: 'Well, it's so clean.'
Customer: 'It's certainly uncontaminated by cheese.'
""")
When you use three quotes not only it won't give you a syntax error, but it will also start a new
line when you write the code as we did above.

Arrays
Arrays In Python
Create a new file called arrays.py
What are arrays in python? It is similar to arrays in any other languages such as C/Ruby. Array
is a collection of items which can be of any type(strings, integers etc.)

Character Arrays: each character/array in python should be addressed by a variable let's see
how
newArray = ["mashrur", "New York", "USA"]
print newArray

Here the array has been assigned to a variable "newArray" you can choose anything and then is
being printed using "print" command.
In order to Run it, All you have to do is this run the arrays.py using the following command in
terminal python arrays.py
Unicode Arrays in Python: Unicode arrays are used to respond to the 'u' typecode corresponds
to Python’s unicode character.
This won't work reason being, you need to define the encoding type at the start of your file like
this "# coding=<encoding name>".

So go to the top of your arrays.py file and add "# coding=UTF8"


On narrow Unicode builds this is 2-bytes, on wide builds this is 4-bytes. for example.
uniArray = [u'hello', u'NewYork City']
print uniArray

In the code above, we passed on a unicode value for array, defining it using 'u' typecode. So
here u preceding 'hello' defines the encoding type of the data passed along is that of unicode
Then we printed it using 'print'

Numerical Array
Let's see the Numerical Arrays now. The procedure is sam, the only thing is you don't need the
quotes ''. Below is an example

numArray = [1, 2, 3, 4, 5]
print numArray

Let's see the Floating Array, Floating arrays are the ones where the numbers contain decimal
points.
floatArray = [1.0, 2.0, 3.0, 4.0, 5.0]
print floatArray

Getting values from array.


Printing the specific values of an array can be performed by using the value position. for eg:
print newArray[1]
In the above method, we printed the second value that is stored in "newArray". Array always
start at index "0". So let's say you want to call the first value of newArray, you need to do
something like this:
print newArray[0]
Now Run the file and see the results

Modifying an existing Array


Sometimes you might want to modify what you already have in that array or just add more to the
array data.
in your IDE create a new file modifyarray.py (you can name it anything)
We will look into it in this section.

newArray = ["Mashrur", "NewYork", "[email protected]"]


print newArray
newArray[1] = "Germany"

In above example I have modified the second value of the array from New York to Germany.
print "Array is Modified, New Array is: "
print newArray

Let's see one more example


newArray[2] = "[email protected]"
print newArray

This is how you actually modify the elements within an array


But what if you want to add something to the array? Let's see how it is done.
We are going to modify newArray.
In new array we have 3 elements at position: 0, 1 and 2. Now we would like to add another thing
to position 3.

newArray.append("edinburgh")
print newArray
Here you can see we've just added a value to the existing array.
Note with append, you will only be able to add one value. well can I add more than one value?
Yes, you can.
Let's try adding more than one value of different type codes using extend
newArray.extend(["gold", 12, 1.5])
print newArray
The above example extends the array to any length, along with the values you might need to
add. These can be of any typecode.
Removing the data in an array:
Let's say we want to remove the second element from the array, so let's try the same in
following example
newArray.remove("gold")

So in above example we wanted to remove one of the elements of newArray, which is "gold".
So we've used .remove with the .remove function with the element that we want to remove.
print newArray
That's basically it about modifying the arrays. Try out a few by your own by creating new Arrays
and modifying them.

Hashes
Create a new file called hashes.py
Hashes, or dictionaries, are similar to arrays but exist in key, value pairs. They are containers
for data, but hashes are a lot more complex due to the key, value pairing.

The uses of a dictionary


Dictionaries ,just like lists, are one of the most commonly used data structures in programming
A dictionary is used to map or associate things you want to store to keys you need to get them.

Let’s look at a hash:

odin = {'name': 'Odin', 'age': 6000, 'height': 3 * 3 + 9 / 5}


print odin['name']
This will print Odin

print odin['age']
This will print 6000

print odin['height']
This will print 10

We can also add things to our hashes on the fly. Let’s see an example:
odin['city'] = 'Asgard'

print odin['city']
This will print Asgard

print odin
This will print the whole hash
Ok, so we've seen that we can use strings in order to get informations out of a hash. But, if you
want to use integers (numbers) you can do like so:

thor = {1: 'Thor', 2: '2000', 3: 'Asgard'}

Alright, now that we have our hash. Let’s see if it works


print thor[1]

This will give us Thor

print thor[2]
This will give us 2000

print thor[3]
This will give us Asgard

Now, what do we do if we put something we do not need inside a dictionary and we want to
delete it?
Simple, we use the del keyword

del thor[2]
print thor

Let’s create an awesome dictionary.

We will create a dictionary of how the days of the week got their name
days = {
'Sunday':
"""
Sun's Day.
The Sun gave people light and warmth every day.
They decided to name the first (or last) day of the week after the Sun.
""",
'Monday':
"""
Moon's Day.
The Moon was thought to be very important in the lives of people and their crops.
""",
'Tuesday':
"""
Tiw's Day.
Tiw, or Tyr, was a Norse god known for his sense of justice
""",
'Wednesday':
"""
Woden's Day.
Woden, or Odin, was a Norse god who was one of the most powerful of them all
""",
'Thursday':
"""
Thor's Day.
Thor was a Norse god who wielded a giant hammer.
""",
'Friday':
"""
Frigg's Day.
Frigg was a Norse god equal in power to Odin.
"""
}

print '=' * 15
print "The name of the last/first day of the week, Sunday, comes from: ", days['Sunday']
print "The the name of the first/second day of the week, Monday, comes from: ", days['Monday']
print "The name of the second/third day of the week, Tuesday, comes from: ", days['Tuesday']
print "The name of the third/fourth day of the week, Wednesday, comes from: ",
days['Wednesday']
print "The name of the forth/fifth day of the week, Thursday, comes from: ", days['Thursday']
print "The name of the fifth/sixth day of the week, Friday, comes from: ", days['Friday']

This will create a dictionary which prints the meaning of all the days of the week.
Run the file and see how it is

Branches
Create a new file called branches.py
Alright, so you've learned how to say 'Hello World' in Python, you learned how to do math and
print certain things.
You've learned what arrays are and how to use them and also hashes a.k.a dictionaries
Now, let’s dive into branches and functions

If statements

humans = 20
dinosaurs = 30
pterodactyls = 25

if humans < dinosaurs:


print "Dinosaurs are alive! We've done it, now they are going to eat us!"

if humans > dinosaurs:


print "We were not able to bring dinosaurs back.. how sad"

if humans < pterodactyls:


print "Is that a plane? Is that a helicopter? Is that superman? NO! It’s a pterodactyls!"

if humans > pterodactyls:


print "This one failed as well... he can't fly."

What is an if-statement? An if-statement creates what is called a branch in the code. The if-
statement tells your script "If this expression is True, then run the code under it. otherwise skip
it"
In order to create a branch (like the if statement above) you need to have a colon at the end of
the line, and also the code inside it needs to be indented
Do not forget that Python is very picky, so it won't accept syntax errors, having the tab for
indentation is a must (signifying the code block)

If, elseif, else

humans = 15
cats = 20
dogs = 15

if cats > humans:


print "It’s over. The cats have conquered the earth!"
elif cats < humans:
print "We won, the cats are not a danger anymore!"
else:
print "We are still fighting them!"

if dogs > cats:


print "The never ending fight between dogs and cats is over! Dogs have won!"
elif dogs < cats:
print "The never ending fight between dogs and cats is over! The cats have won!"
else:
"Same old story, they are fighting again"

Alright, so here is our example. Lets explain what it does:


The same as my example with the if-statement, if A is true then print A. if A is false then print B.
But that was on one line, if we want something more complex we can use the elif and else
statements.
The above says : If A is true then print A. If A is not true and B is true, then print B. And if neither
A nor B are true, print C

Functions
Functions are used for a new things:
1. Extract common logic so you don’t have to keep typing them out
2. They take arguments and perform that logic/computation on the arguments and return
something to the caller

Example:
def print_two_arg(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)

def print_one(arg1):
print "arg1: %r" % arg1

print_two_arg("Odin", "Thor")
print_one("Here is only one argument")

Above we have two functions, the first one takes two arguments (We pass in Odin and Thor)
and the second one takes only one argument
This is how the flow of an function goes, you put an argument and then you work with it.
You might ask, what is def, why do we use it? Well, def stands for define, its what defines that
the code you put there is actually a function, when you have a defined function you can use it
anywhere else in your code. Like we do below the definition, we are calling the function which is
going to print the arguments
Object Oriented Programming
Create a new file called oop.py
OOP with Python

Let say I have a class music and have nodes defined in it. Now I made another class called
"Musician" and want the property of music to be added into it. So how am I supposed to do
that? All I have to do is apply inheritance into it
Let's see an example

class Music:
def notes(self, note):
self.data = note

def display(self):
print self.data

x = Music()
y = Music()

x.notes("la la la la la la")
y.notes("rum pum pum dum dum")

x.display()
y.display()

What we did here is we defined a class and created two instances of the class
In the second line we defined the class methods using "def".
Then we added a self instance.
Then Again we've defined another class method to display everything from previous class
method.
Further, we've printed the self.data instance value. Let's see how this works.
Try running the program in the terminal and see what result you get.

Now let's see how the class that we've added right now would make it easier to get the work
done.
so as we saw that we have our class, now we want to utilize it right. let's see how our
"Inheritance” concept would work here
Add the following to the program
class Musician(Music):
def display(self):
print 'The notes are = "%s"'% self.data

mashrur = Musician()
mashrur.notes("no rhythm in these notes")
mashrur.display()

In the above example we inherited the Music class by adding it within () This would let us use
the Music class methods in Musician class.
Next we define the display class method for Musician to make it work differently than Music
class.
Print the data using the self.data from Music class, which is the superclass. Going further, we
will print a random statement which would include self.data from parent class.
The self.data that would be printed here will be the data we set in next step
In next step we will set the new(empty) object mashrur, then using notes function again in
Musician class we set up a value for mashrur.

First Python Project:


Compound Interest Calculator

Create a new file called ci.py

def compound_interest():
principal = input('Please enter your initial deposit: $')
rate = input('Please enter the interest rate: ')
rate = rate / 100.0
time = input('Please enter the number of years it will be saved: ')
time += 1
compound = input('How many times is the interest compounded a year?: ')

print "Year %21s" % "Amount on deposit"

for time in range(1, time):


formula = principal * (1.0 + rate)** time
print "%4d%21.2f" % (time, formula)

def start():
print "Lets start compounding your interest."
compound_interest()

start()

In the above code we calculate the compound interest


We start by defining a function (compound_interest)

Then we are asking for a couple of input elements from the user:
Initial deposit, rate (which we divide by 100), the number of years(incrementing it by 1 each
year), then we are asking for the number of times you want to calculate the CI in a particular
year

We are then printing two strings, year and amount on deposit, the first string also adds space
with %21s, just to keep it clean and simple.

The next step we are doing a for loop with time, we are calculating the principal * 1.0 + rate **
time.
And then printing the result (time is the year, and formula is the result)
In the second function we are defining start and then we are calling the compound_interest
And our last step is to call start outside the function and start the program
Second Python Project:
Loan Amortizator Calculator
Create a new file called amortization.py
Note: In order to run this file later on, follow these steps:
1- type in your terminal ‘python’
2- import amortization
3- amortization.amortization(15000, 5, 350)
(amount of money, rate, days)
4- to exit python console/terminal, hit ctrl-d

from decimal import *


Basically the Amortization consists of decimal points. In order to get the decimals to work the
way we want, we have to import everything from the python module called decimal

def amortization(principal, rate, term):


# first we define a function which would call a function called amortization in order to populate
our table.
# We would need to define the fields that would be required from the user. (principal, rate and
term)
# Print the amortization table for a loan given the principal, the interest rate, and
# the term (in months).

# here the payment variable is called upon to hold the three values provided by the user as
mentioned earlier
# Beginning balance will show the Principal amount that is being paid
# Time to Print headers of our Amortization table using print table. I will explain a few things
used in this table
payment = pmt(principal, rate, term)
begBal = principal
print 'Pmt no'.rjust(6), ' ', 'Beg. bal.'.ljust(13), ' ',
print 'Payment'.ljust(9), ' ', 'Principal'.ljust(9), ' ',
print 'Interest'.ljust(9), ' ', 'End. bal.'.ljust(13)
print ''.rjust(6, '-'), ' ', ''.ljust(13, '-'), ' ',
print ''.rjust(9, '-'), ' ', ''.ljust(9, '-'), ' ',
print ''.rjust(9, '-'), ' ', ''.ljust(13, '-'), ' '
# the rjust and ljust are used to set the justification alignment for the table columns
# Okay now comes the time to Print data that we get from our calculations
for num in range(1, term + 1):
# there goes the for loop
interest = round(begBal * (rate / (12 * 100.0)), 2)
applied = round(payment - interest, 2)
endBal = round(begBal - applied, 2)
# Then we'll apply the formulas to calculate amortization using proper variables
print str(num).center(6), ' ',
print '{0:,.2f}'.format(begBal).rjust(13), ' ',
print '{0:,.2f}'.format(payment).rjust(9), ' ',
print '{0:,.2f}'.format(applied).rjust(9), ' ',
print '{0:,.2f}'.format(interest).rjust(9), ' ',
print '{0:,.2f}'.format(endBal).rjust(13)
# In this example str changes the values that is in for loop of num
# 0:,.2f This value here is actually changing the results to 2 digits of decimal points. We are
applying the .format to format it in the right column with right justifications
begBal = endBal
# At the end we are setting begBal to be same as the end balance for next iteration of the
loop
def pmt(principal, rate, term):
# Calculates the payment on a loan.
# Returns the payment amount on a loan given the principal, the interest rate and term

ratePerTwelve = rate / (12 * 100.0) # here we define how we are calculating the amortization.
result = principal * (ratePerTwelve / (1 - (1 + ratePerTwelve) ** (-term)))
# Once we have the rate per year calculated, we calculate result applying the formula above.
result = Decimal(result)
result = round(result, 2)
return result
# Convert result to decimal and round off to two decimal places.

Third Python Project:


Tic Tac Toe - Game
Create a new file called tictactoe.py
#encoding: UTF-8
import random

We import random in order to be able to use the random method in our script

We will start by drawing the board.


This will create 3 rows (like the classic tic tac toe, we are not looking to make a new game here)

def drawBoard(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')

Then we will ask for some input from the player.

def inputPlayerLetter():
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = raw_input().upper()
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']

In the code above we are checking if the variable letter has stored any value (X or O)
Then we are priting a message asking for the user to put in what letter he wishes to use
We are receiving input with raw_input (just input in other versions of Python. We are using
2.7.6)
We also store the value in the same line and we uppercase it (just to be safe)
After that we have a logic wich will determine the AI's (Artificial Intelligence) letter.
If X then O if O then X

Now we should work on the logic that will randomize who goes first.
Since we already imported random we can freely use that function.
We will use it below, we will do a simple if statement and randomize who goes first.

def whoGoesFirst():
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'

Now we will work on the logic that will handle the play again statement.
It’s quite simple, we print a message and we ask for some input.
I will return True if the player writes anything that starts with Y (and it will be lowercased just to
be safe)

def playAgain():
print('Do you want to play again? (yes or no)')
return raw_input().lower().startswith('y')

This is the logic that will make the move. It takes three arguments: board, letter, move (1-9)

def makeMove(board, letter, move):


board[move] = letter

Here we will check who the winner is.


This function takes 2 arguments and it checks each move on the board (1,2,3,4,5,6,7,8,9) with
the letter. if the letter has the most board moves then it wins.

def isWinner(board, letter):


return ((board[7] == letter and board[8] == letter and board[9] == letter) or # across the top
(board[4] == letter and board[5] == letter and board[6] == letter) or # across the middle
(board[1] == letter and board[2] == letter and board[3] == letter) or # across the bottom
(board[7] == letter and board[4] == letter and board[1] == letter) or # down the left side
(board[8] == letter and board[5] == letter and board[2] == letter) or # down the middle
(board[9] == letter and board[6] == letter and board[3] == letter) or # down the right side
(board[7] == letter and board[5] == letter and board[3] == letter) or # diagonal
(board[9] == letter and board[5] == letter and board[1] == letter)) # diagonal
def getBoardCopy(board):
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard

In above piece of code, we invoked an instance of the board by defining it as a new function
getBoardCopy, inheriting the board parent class
Then we defined and empty variable called dupeboard and looped thru it.
In last line we returned the value that would get assigned to dupeboard

Here we will check if there is any space free on the board. If there is not then we will return an
empty variable.

def isSpaceFree(board, move):


return board[move] == ' '

def getPlayerMove(board):
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = raw_input()
return int(move)
In the code above we ask for the players next move.
We are starting with an empty variable (move) and then we have a while loop which would loop
thru the moves (1-9) that are being captured from user input or else if there is no space left on
the board it would not run that while loop for "move"
In next line we ask for user input with a prompt.

def chooseRandomMoveFromList(board, movesList):


possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)

if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
Here we are choosing a random move from the available moves.
We are doing a for loop and checking which space is free, therefore, checking which moves are
available.
On the second if we are checking the length (len) of the possibleMoves, and we are making
sure that it’s not equal to 0
Then we are returning one of the possible moves randomly.
Else, return none

def getComputerMove(board, computerLetter):


# This is to initialize the board for the computer, and ask the AI to choose the letter for the
move as per its desired
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'

# This if loop is to determine what letter the computer chose.


# First, check if we can win in the next move
# We are doing a loop and we check if there is any free space.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):

makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i

# Check if the player could win on their next move.


for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i

# Try to take one of the corners, if they are free.


move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move

# Try to take the center, if it is free.


if isSpaceFree(board, 5):
return 5

# Move on one of the sides.


return chooseRandomMoveFromList(board, [2, 4, 6, 8])

def isBoardFull(board):
# Return True if every space on the board has been taken. Otherwise return False.
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True

print('Hello. This is a Tic Tac Toe game. Enjoy!')


Print a message before starting the game

while True:
# Reset the board
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
# Player’s turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard, playerLetter, move)

if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
print('Hooray! You have won the game!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'computer'
else:
# Computer’s turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)

if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'

if not playAgain():
break
If we are going to end up the game, we will use break to end the while loop we're running

Most of the code above is self explanatory, but I will give my best to explain it better.
While True = If the board is full, then reseat the board.
Get the player and computer letter and player input
start the function that decides who goes first
Print a text
The variable gameIsPLaying (we will use it to decide when the game is playing and when not) is
set to true
Do a while loop while (heh) the game is playing, if the turn is for the player: draw the board,
move (get input of the move) make the move and then if its winner draw the board, print some
text and put the variable gameIsPLaying to false
If the board is full, draw the board, print a text and break (stop) the logic
Else, allow the computer to make the move

If the move is for the computer, then its just the same cose as above.

You might also like