Python Learning Documentation
Python Learning Documentation
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
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
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:
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
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.
Let’s say that we want our string to be on multiple lanes, how would we do that?
We can use the keyword \n
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>".
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
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
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.
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:
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
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
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)
humans = 15
cats = 20
dogs = 15
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.
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?: ')
def start():
print "Lets start compounding your interest."
compound_interest()
start()
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
# 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.
We import random in order to be able to use the random method in our script
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(' | |')
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)
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 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.
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
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i
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
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.