Codeacademy Python
Codeacademy Python
Python
Author: Howell
CodeAcademy Python
Introduction
String
String Formatting
Function
Import Module (Library)
Dictionary
Editing a Dictionary
Dictionary with Multiple Type of Values
Example of Dictionary
Example of Dictionary
Loop
While loop
Multiple List (zip)
For / Else
More Combined Examples
Iterators
Iterators for Dictionaries
List Comprehension
List Slicing Syntax
Function Programming
Class
Base form
Scope
Member Variables
Example
Inheritance
Override
Example of Class
Example of Inheritance
Example of Overriding
Overriding Method
Introduction
#Creating a variable
my_variable = 10
my_bool = True
my_float = 1.23
#Exponential
eggs = 10**2
#Modulo (remainder)
spam = 3 % 2
String
#Escaping character
"""
'There's a snake in my boot!'
This code breaks because Python thinks the apostrophe in 'There's'
ends the string.
We can use the backslash to fix the problem, like this:
'There\'s a snake in my boot!'
"""
'This isn\'t flying, this is falling with style!'
#Access by Index
"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5
#String methond
parrot = "Norwegian Blue"
len(parrot) #Get the length of parrot.
parrot.lower() #De-capitalize all the letters.
parrot.upper() #Capitalize all the letters.
str(3.14) #turns non-strings into strings, useful when combining nu
mber with string.
#e.g. print "The value of pi is around " + str(3.14)
def digit_sum(n):
total = 0
for i in str(n): #Foce n to be a string.
total += int(i) #Force i to be an int.
return total
thing = "spam!"
for l in thing:
print l #Print out every letter perpendicularly.
print l, #Print out every letter on the same line.
#Dote notation
"""
Methods that use dot notation only work with strings.
On the other hand, len() and str() can work on other data types.
"""
String Formatting
"""
Use % operator to combine a string with a variable.
% operator will replace a %s in the string with the string variable
that comes after it.
"""
string_1 = "Camelot"
string_2 = "place"
#Multiple addition
"""
You need the same number of %s terms in a string as the number of v
ariables in parentheses
"""
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
#or
True or False
#not
not 3**4 < 4**3
not not False
"""
Evaluation order: first not, and, or last.
"""
If statement
def greater_less_equal_5(answer):
if answer>5:
return 1
elif answer<5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
Function
def square(n): #Header, n is a parameter.
"""Returns the square of a number."""
squared = n**2
print "%d squared is %d." % (n, squared)
return squared
"""
If we only need to use sqrt, we can import in this way so
we do not have to type math.import over and over again.
math is a module and sqrt() is a function.
"""
from math import sqrt
#Universal import
"""
Import everything from the math module so we do not have to retype
it.
Universal import is generally not good since there might be some co
nflict with its function name and your function name.
"""
from math import *
List
#Declare a list by adding elements to it.
zoo_animals = ["MIFFY","pig", "sloth"];
#Remove an element.
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')
n = [1, 3, 5 1]
n.pop(1) #removes 3 (the item at index 1)
n.remove(1) #remove 1 (find the item and remove it (once))
del(n[1]) #remove 3
List Slicing
String Slicing
animals = "catdogfrog"
#The first three characters of animals
cat = animals[:3]
#The fourth through sixth characters
dog = animals[3:6]
#From the seventh character to the end
frog = animals[6:]
start_list = [5, 3, 1, 2, 4]
square_list = []
print square_list
#Method 2
for i in range(len(list)):
print list[i]
#Example
n = ["Michael", "Lieberman"]
def join_strings(words):
result = ""
#Method 1
for word in words:
result += word
return result
#Mehod 2
for i in range(len(words)):
result += words[i]
return result
print join_strings(n)
a = [1, 2, 3]
b = [4, 5, 6]
print a + b #prints [1, 2, 3, 4, 5, 6]
List of List
Battleship Example
#You can hide your battle in the map and the player is going to gue
ss where it is.
board = []
for i in range(0,5):
temp = ["O"] * 5
board.append(temp)
print board #Print a grid with 5 x 5 "O"
print ship_row
print ship_col
Function
Import Module (Library)
Dictionary
Editing a Dictionary
Dictionary with Multiple Type of Values
Example of Dictionary
Example of Dictionary
Loop
While loop
Multiple List (zip)
For / Else
More Combined Examples
Iterators
Iterators for Dictionaries
List Comprehension
List Slicing Syntax
Function Programming
Class
Base form
Scope
Member Variables
Example
Inheritance
Override
Example of Class
Example of Inheritance
Example of Overriding
Overriding Method
Dictionary
"""
Dictionary uses key-value pairs to link keys and values.
We can use key to access values.
e.g. Phone books.
"""
Editing a Dictionary
#Add new values
menu = {} #Empty dictionary.
menu["Miffy"] = 520
menu["Miffy little pig"] = 521
menu["Miff"] = 521 #A value can have multiple keys associated with
it.
inventory = {
'gold' : 500, #Add a coma between each key
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list
to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
inventory['backpack'].remove('dagger')
inventory['gold']=[50,550]
Example of Dictionary
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
Example of Dictionary
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >=80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
my_class = [lloyd, alice, tyler]
print get_class_average(my_class)
Loop
While loop
#While loop
count = 0
while True: #Condition
print count
count += 1 #Index
if count >= 10:
break
#While / Else
import random
count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"
#print out index as well.
choices = ['pizza', 'pasta', 'salad', 'nachos']
"""
zip creates pairs of elements passed two lists, and will stop at th
e end of the shorter list.
"""
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
For / Else
"""
the else statement is executed after the for, but only if the for e
nds normallythat is, not with a break.
"""
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
def scrabble_score(word):
total = 0
for l in word:
temp = l.lower()
total += score[temp]
return total
Iterators
List Comprehension
#Print 6
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]
Function Programming
"""
Anonymous Function
We don't need to give the function a name but it works the same as
a well-defined function.
"""
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list) #[0, 3, 6, 9, 12, 15]
#fileter(lambda x: (return condition of x), (source))
#In Python, you can write numbers in binary format by starting the
number with 0b.
print 0b1, #1
print 0b10, #2
print 0b11, #3
print 0b100, #4
print 0b101, #5
print 0b110, #6
print 0b111 #7
print "******"
print 0b1 + 0b11 #4
print 0b11 * 0b11 #9
bin() Function
#bin() takes an integer as input and returns the binary representat
ion of that integer in a string.
for i in range(1,6):
print bin(i)
int Function
#Specify number base, then the number will be converted to base 10.
print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
print int("11001001",2)
shift_right = 0b1100
shift_left = 0b1
shift_right = shift_right >> 2
shift_left = shift_left << 2
print bin(shift_right) #0b11
print bin(shift_left) #0b100
Bitwise Comparison
#And operator
"""
The bitwise AND (&) operator compares two numbers on a bit level an
d returns a number where the bits of that number are turned on if t
he corresponding bits of both numbers are 1.
e.g.
a: 00101010 42
b: 00001111 15
===================
a & b: 00001010 10
#Or operator
"""
The bitwise OR (|) operator compares two numbers on a bit level and
returns a number where the bits of that number are turned on if eit
her of the corresponding bits of either number are 1.
i.e. only 0 | 0 = 0
e.g.
a: 00101010 42
b: 00001111 15
================
a | b: 00101111 47
"""
print bin(0b1110 | 0b101) #0b1111
#XOR operator
"""
The XOR (^) or exclusive or operator compares two numbers on a bit
level and returns a number where the bits of that number are turned
on if either of the corresponding bits of the two numbers are 1, bu
t not both.
i.e.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
"""
print bin(0b1110 ^ 0b101) #0b1011
Example
#A function that will check whether the 4th bit from the right is t
urned on (1).
def check_bit4(input):
mask = 0b1000
desired = input & mask
if desired > 0:
return "on"
else:
return "off"
Class
Base form
"""A class called Animal inherits from class object"""
class Animal(object):
pass #An expected expression when class is empty.
"""
The part that is magic is the fact that self is the first parameter
passed to __init__(). Python will use the first parameter that __in
it__() receives to refer to the object being created; this is why i
t's often called self, since this parameter gives the object being
created its identity.
"""
class Animal(object):
def __init__(self,name):
self.name = name
"""Instantiating object"""
class Animal(object):
def __init__(self,name):
self.name = name
zebra = Animal("Jeffrey")
print zebra.name #Print out 'Jeffery'
"""More parameter"""
class Animal(object):
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry
Scope
Member Variables
class Animal(object):
"""Makes cute animals."""
is_alive = True
health = "good"
def description(self):
print self.name
print self.age
Example
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
my_cart = ShoppingCart("Howell")
my_cart.add_item("bra", 10000)
Inheritance
Override
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
class PartTimeEmployee(Employee):
#PartTimeEmployee.calculate_wage overrides
#Employee.calculate_wage
def calculate_wage(self,hours):
self.hours = hours
return hours * 12.00
milton = PartTimeEmployee("miffy")
print milton.full_time_wage(10) #Still $20/h
Example of Class
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color,self.mod
el,str(self.mpg))
def drive_car(self):
self.condition = "used"
Example of Inheritance
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
#Create a subclass.
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type = battery_type
Car.__init__(self, model, color, mpg)
Example of Overriding
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color,self.mod
el,str(self.mpg))
def drive_car(self):
self.condition = "used"
class ElectricCar(Car):
def __init__(self,model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type=battery_type
def drive_car(self):
self.condition = "like new"
Overriding Method
#The use of __repr__()
class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point
Open a File
Write to a File
for i in my_list:
temp = str(i) + "\n"
my_file.write(temp)
The reason why we need to close our file once we are done with it:
During the I/O process, data is buffered: this means that it is held in a temporary location
before being written to the file.
Python doesnt flush the bufferthat is, write data to the fileuntil its sure youre done
writing. One way to do this is to close the file. If you write to a file without closing, the data
wont make it to the target file.