CodeAcademyNotes Python
CodeAcademyNotes Python
Comparators - check if value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value
6 Comparators:
1) Equal to
2) Not Equal to
3) Less than
4) Less than or Equal to
5) Greater than
6) Greater than or Equal to >=
==
!=
<
<=
>
Input
raw_input() - accepts a string, prints it, and then waits for the user to type something and press
Enter (or Return)
PygLatin Exercise: 4/11 - exercise attempts a validation code through counting the number of characters in the
input function
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0:
print original
else:
print "empty"
def square(n):
"""Returns the square of a number."""
squared = n**2
print "%d squared is %d." % (n, squared)
return squared
Functions Exercise 4/19 - Parameters and Arguments
Parameter - acts as a variable name for a passed in argument
Ex:
def square(n): Here, the parameter is n. When the n = 10, 10 is the argument
Functions Exercise 5/19 - Functions Calling Functions (Nested Function)
Ex:
def fun_one(n):
return n*5
def fun_two(m):
return fun_one(m) + 7
Functions Exercise 6/19 - Function Syntax Practice
def cube(number):
return number**3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
print "n is NOT divisible by 3"
def cube(number):
return number**3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
print "n is NOT divisible by 3"
Importing Models Exercise 7/19
Module - a file that contains definitions - including variables and functions - that you can use once it
is imported.
Ex:
import this
math.sqrt() inefficient
easier method: type from math import sqrt() now you can just use sqrt()
standard form: from module import function
abs() function gives you absolute value (magnitude of number regardless of sign) of any number
index - is an address that identifies the item's place in the list. The index appears directly after the
Python Lists and Dictionaries Ex 4/14 - Adding strings to lists and list length
A list doesn't have to have a fixed length. You can add items to the end of a list any time you like.
suitcase = []
suitcase.append("sunglasses")
# Your code here!
suitcase.append("sunblock")
suitcase.append("bathing suit")
suitcase.append("sandals")
list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase
Python Lists and Dictionaries Ex 5/14 - List Slicing
Ex:
letters = [a, b, c, d, e]
slice = letters[1:3] Includes the index before the colon BUT NOT the index after the colon
print slice
print letters
Exercise:
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # The first and second items (index zero and one)
middle = suitcase[2:4] # Third and fourth items (index two and three)
last = suitcase[4:] # The last two items (index four and five)
Python Lists and Dictionaries Ex 6/14 - String Slicing
You can slice a string exactly like a list! In fact, you can think of strings as lists of characters: each
character is a sequential item in the list, starting from index 0.
animals = "catdogfrog"
cat = animals[:3] # The first three characters of animals
dog = animals[3:6] # The fourth through sixth characters
frog = animals[6:] # From the seventh character to the end
Python Lists and Dictionaries Ex 7/14 - Searching and Inserting Strings in a List
To search for a string:
animals = ["ant", "bat", "cat"]
print animals.index("bat")
To insert a string:
animals.insert(1, "dog")
print animals
Exercise:
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
animals.insert(duck_index, "cobra") # Your code here!
print animals # Observe what prints after the insert operation
Python Lists and Dictionaries Ex 8/14 - For Loops
can use For loop to do something w/ every item in a list.
A variable name follows the for keyword; it will be assigned the value of each list item in turn.
Then in list_name designates list_name as the list the loop will work on. The line ends with a
colon (:) and the indented code that follows it will be executed once per item in the list.
Standard Form:
for variable in list_name:
# Do stuff!
Exercise:
my_list = [1,9,3,8,5,7]
for number in my_list:
print 2 * number
2.
start_list = [5, 3, 1, 2, 4]
square_list = []
for numbers in start_list: # Your code here!
square_list.append(numbers ** 2)
print square_list.sort()
Python Lists and Dictionaries Ex 10/14 - Definition of Keys and Dictionaries
dictionary similar to a list but values are accessed through keys instead of indexes; enclosed
using the character: { }
Standard Form: d = {key 1 : 1, key 2 : 2, key 3 : 3}
this dictionary is called d
has 3 key pairs
key 1 points to value 1, key 2 points, etc.
used for phone numbers and emails
# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin'] # Prints Puffin's room number
print residents['Sloth'] # Prints Sloth's room number
print residents['Burmese Python'] #Prints BP's room number
Python Lists and Dictionaries Ex 11/14 - New Entries in Dictionaries
Dictionaries can be changed after they are created; can add new key/value pairs to dictionary
Ex: dict_name[new_key] = new_value
empty pair of curly braces {} is an empty list
when using len() on a dictionary, it counts the key-value pairs it has; each pair only counts once,
even if the value is a list
can put lists inside dictionaries
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
menu['Spagetti'] = 10.99
menu['Ceaser Salad'] = 5.99
menu['Toasted Raviolli'] = 5.99 # Your code here: Add some dish-price pairs to menu!
Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and
'lint'
3.
.sort() the items in the list stored under the 'backpack' key
4.
Then .remove('dagger') from the list of items stored under the 'backpack' key
5.
inventory = {
'gold' : 500 + 50,
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'],
Like step 2 above, loop through each item in the list called a.
2.
Like step 3 above, if the number is even, print it out. You can test if the item % 2 == 0 to help
you out.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for x in a:
10
if x % 2 == 0:
print x
Day at the Supermarket EX 3/13 - Lists + Functions
1. Write a function called fizz_count that takes a list x as input.
2.
3.
for each item in x:, if that item is equal to the string "fizz" then increment the count variable.
4.
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
Day at the Supermarket EX 6/13 - Creating a Dictionary + Format
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for key in prices:
total = total + (prices[key] * stock[key])
print total
Day at the Supermarket EX 11/13 - Compute Bill function
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
11
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for fruit in food:
total = total + prices[fruit]
return total
food = shopping_list
print compute_bill(food)
Day at the Supermarket EX 11/13 - Removing stock after count
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for fruit in food:
if stock[fruit] > 0:
total = total + prices[fruit]
stock[fruit] = stock[fruit] - 1
return total
needs to be indented w/ the for-loop, not the if-statement
Student Becomes Teacher EX 1/9 - Dictionary Review
lloyd = {
"name": "Lloyd",
"homework": [],
"quizzes": [],
"tests": [],
}
alice = {
"name": "Alice",
"homework": [],
12
"quizzes": [],
"tests": [],
}
tyler = {"name": "Tyler",
"homework": [],
"quizzes": [],
"tests": [],
}
Student Becomes the Teacher EX 4/9 - Lists and Stuff
students = [lloyd, alice, tyler]
for student in students:
print student["name"]
print student["homework"]
print student["quizzes"]
print student["tests"]
Student Becomes the Teacher EX 5/9 - Floats and Division
def average(numbers):
total = sum(numbers)
return float(total) / len(numbers)
Student Becomes the Teacher EX 6/9 - Weighted Avg.
The \ character is a continuation character. The following line is considered a continuation of the
current line.
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return homework*.1 + quizzes *.3 + tests*.6
13
3. For each student item in the class list, calculate get_average(student) and then call
results.append() with that result.
4. Finally, return the result of calling average() with results.
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
Student Becomes the Teacher 9/9 - Final Portion
1. Finally, print out the result of calling get_class_average with your students list. Your students should
be [lloyd, alice, tyler].
2. Then, print the result of get_letter_grade for the class's average.
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]
}
students = [lloyd, alice, tyler]
# Add your function below!
def average(numbers):
total = sum(numbers)
return float(total) / len(numbers)
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return homework*.1 + quizzes *.3 + tests*.6
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
14
return "D"
else:
return "F"
print get_letter_grade(lloyd)
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
print get_class_average(students)
print get_letter_grade(get_class_average(students))
List Recap 2/18 - List Element Modification
n = [1, 3, 5]
# Do your multiplication here
n.insert(1, n[1] * 5)
n.remove(n[2])
print n
List Recap 2/18 - Removing Elements from Lists
Three options on removing items from lists:
New
n.pop(index) - will remove the item at index from the list and return it to you
n.remove(item) - will remove the actual item if it finds it
del(n[index]) - is like .pop in that it will remove the item a the given index, but it wont return it
Functions Recap 7/18 - Strings in Functions (Concatenated)
n = "Hello"
# Your function here!
def string_function(s):
return s + "world"
print string_function(n)
Functions Recap 10/18 - Modifying an element of a list in a function
Change list_function so that:
1. Add 3 to the item at index one of the list.
2. Store the result back into index one.
3. Return the list.
def list_function(x):
x[1] = x[1] + 3
return x
n = [3, 5, 7]
print list_function(n)
Functions Recap 10/18 - Modifying an element of a list in a function
1. Define a function called list_extender that has one parameter lst.
2. Inside the function, append the number 9 to lst.
15
3.
n = [3, 5, 7]
# Add your function here
def list_extender(lst):
list.append(lst)
return lst
print list_extender(n)
Functions Recap 11/18 - Printing out a list item by item in a function
1.
2.
3.
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print x[i]
print print_list(n)
Create a function called double_list that takes a single argument x (which will be a list) and
multiplies each element by 2 and returns that list. Use the existing code as a scaffold.
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
# Don't forget to return your new list!
print double_list(n)
Functions Recap 14/18 - Range Function
New
range(stop)
range(6)
[0, 1, 2, 3, 4, 5]
range(start, stop)
range(1, 6)
[1, 2, 3, 4, 5]
range(1, 6, 3)
[1, 4]
in all cases, range function returns a list of numbers from start up to (but not including) stop; each
16
New
1.
On line 3, define a function called total that accepts one argument called numbers. It will be a
2.
Inside the function, create a variable called result and set it to zero.
3.
Using one of the two methods above, iterate through the numbers list.
4.
5.
list.
n = [3, 5, 7]
def total(numbers):
result = 0
for x in range(len(numbers)):
result = result + numbers[x]
return result
Define a function called join_strings accepts an argument called words. It will be a list.
2.
Inside the function, create a variable called result and set it to "", an empty string.
3.
Iterate through the words list and append each word to result.
4.
n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
result = ""
for x in words:
result = result + x
17
return result
print join_strings(n)
using mult. lists in a function is no different from just using mult. arguments in a function
1.
On line 4, define a function called join_lists that has two arguments, x and y. They will both be
2.
lists.
m = [1, 2, 3]
n = [4, 5, 6]
def join_lists(x,y):
return x+y
print join_lists(m, n)
New
In the example above, we first create a list containing two items, each of which is a list of numbers.
2.
3.
For each of the two inner lists (as lst), we iterate through the numbers (as item) and print them
out.
We end up printing out:
1
2
3
4
5
6
1.
On line 3, define a function called flatten with one argument called lists.
2.
3.
4.
18
5.
6.
results.append(numbers)
return results
print flatten(n)
2.
Inside the loop, .append() a list containing 5 "O"s to board, just like in the example above.
Note that these are capital letter "O" and not zeros.
board = []
for x in range(0,5):
board.append(["O"] * 5)
2.
3.
Inside the function, write a for loop to iterates through each row in board and print it to the
screen.
4.
board = []
for x in range(0,5):
board.append(["O"] * 5)
19
def print_board(board):
for x in board:
print x
print print_board(board)
New
Inside your function, inside your for loop, use " " as the separator to .join the elements of each row.
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for x in board:
print " ".join(x)
print print_board(board)
New
1.
Define two new functions, random_row and random_col, that each take board as input.
2.
These functions should return a random row index and a random column index from your board,
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board) - 1)
print random_row(board)
print random_col(board)
1.
New
20
2.
3.
4.
As the last line in your else statement, call print_board(board) again so you can see the "X".
The example above checks if either x or y are outside those ranges. The \ character just continues
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
21
New
condition - expression that decides whether the loop is going to be executed or not
5 steps to this program
1. loop_condition variable set to True
2. while loop checks to see if loop_condition is True. It is, so the loop is entered
3. The print statement is executed
4. The variable loop_condition is set to False
5. The while loop again checks to see if loop_condition is True. It is not, so the loop
is not executed a second time
loop_condition = True
while loop_condition:
print "I am a loop"
loop_condition = False
22
break - one-line statement that means exit the current loop; using break guarantees that the
while True:
print count
count += 1
if count >= 10:
break
While Loops 7-8/19 - While/else statements
while/else similar to if/else but the difference is that the else block will execute anytime the loop
condition is evaluated to False; in other words, else block will execute if loop is never entered or if loop exits
normally
if loop exits as the result of a break, the else will not be executed
from random import randint
guesses_left = 3
# Start your game!
while guesses_left > 0:
guess = int(raw_input("Your guess: "))
if guess == 5:
print "You win!"
break
guesses_left -= 1
else:
print "You lose."
23
New
word = "Marble"
for char in word:
print char,
The example above iterates through each character in word and, in the end, prints out M a r b l e.
The , character after our print statement means that our next print statement keeps printing on
looping over a dictionary will get the key, which can be used to get the value
when going through a loop, python iterates the first key, then the second key, and so on.
On line 5, print the key, followed by a space, followed by the value associated with that key.
for key in d:
# Your code here!
print key,
print d[key]
New
when using for-loops, we dont know the index of the thing we are looking at; useful to know how
each time you go through the loop, index will be one greater, and item will be the next item in the
sequence
similar to using a normal for-loop w/ a list, except this gives us an easy way to count how many
items weve seen so far
We don't want the user to see things listed from index 0, since this looks unnatural. Instead, the
items should appear to start at index 1. Modify the print statement to reflect this behavior.
24
New
zip function will create pairs of elements when passed two lists, and will stop at the end of the
shorter list
zip function can handle 3+ lists as well
Compare each pair of elements and print the larger of the two.
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
25
if f == 'tomato':
print 'A tomato is not a fruit!'
break
print 'A', f
else:
print 'A fine selection of fruits!'
For Loops 19/19 - Own statement
dct = ['eggs', 'milk', 'butter', 'bread']
for x in dct:
if x == 'butter':
print "That can be used for cooking!"
break
else:
print 'A', x
2.
3.
def is_even(x):
if x % 2 == 0:
return True
else:
return False
Practice Lesson 3/15 - round() function
New
def is_int(x):
if x == round(x):
return True
else:
return False
Practice Lesson 4/15 - digit_sum
Write a function called digit_sum that takes a positive integer n as input and returns the sum of all
Assume that the number you are given will always be positive.
26
def digit_sum(n):
total = 0
for x in str(n):
total += int(x)
return total
Practice Lesson 5/15 - factorial exercise
To calculate the factorial of a non-negative integer x, just multiply all the integers from 1 through x.
def factorial(x):
product = 1
while x > 1:
product *= x
x -= 1
return product
prime number = positive integer greater than 1 that has no positive divisors other than 1 and itself.
Define a function called is_prime that takes a number x as input.
For each number n from 2 to x - 1, test if x is evenly divisible by n.
If it is, return False.
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
else:
if x < 2:
return False
elif x == 2:
return True
else:
n=2
while n != x:
if x % n == 0:
return False
n += 1
return True
27
You may not use reversed or [::-1] to help you with this.
2.
You may get a string containing special characters (for example, !, @, or #).
def reverse(text):
new_text = ""
count = len(text)
while count > 0:
char = text[count-1]
new_text = new_text + char
count -= 1
return new_text
Define a function called anti_vowel that takes one string, text, as input and returns the text with
def anti_vowel(text):
vowels = "aeiouAEIOU"
new_text = ""
for char in text:
if char not in vowels:
new_text += char
return new_text
Practice Lesson 9/15 - Scrabble Score
Define a function scrabble_score that takes a string word as input and returns the equivalent scrabble score for
that word.
1.
2.
3.
4.
28
Write a function called censor that takes two strings, text and word, as input. It should return the
29
Don't remove every occurrence, since you need to keep a single occurrence of a number.
30
2.
The order in which you present your output does not matter. So returning [1,2,3] is the same as
returning [3,1,2].
3.
Do not modify the list you take as input! Instead, return a new list.
def remove_duplicates(lst):
count = 0
new_list = []
for i in lst:
if i not in new_list:
new_list.append(i)
count += 1
return new_list
The list can be of any size and the numbers are not guaranteed to be in any particular order.
If the list contains an even number of elements, your function should return the average of the
middle two.
In order to find the median of a list with an even number of elements, you're going to need to find
the indices of the middle two elements.
You can find the middle two elements by halving the length of the array to find the index of the first
element, and subtracting one from the first index to find the second index.
For example, with an array of length 6 like [0,1,2,3,4,5], the two middle elements that need to be
averaged in order find the median would be 2 and 3. You get 3 by cutting the length of the array in half and 2
by subtracting 1 from the previous index: 3. You can use a similar pattern to find the middle element of an
odd-length list.
Last but not least, note that (2 + 3) / 2 is not the same as (2 + 3) / 2.0! The former is integer
division, meaning Python will try to give you an integer back. You'll want a float, so something like (2 + 3) /
2.0 is the way to go.
def median(lst):
lst.sort()
lst_length = len(lst)
if lst_length % 2 == 0:
x = lst[lst_length / 2]
y = lst[(lst_length / 2) - 1]
result = float((x+y)/2.0)
31
elif lst_length % 2 != 0:
result = lst[lst_length / 2]
return result
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average
def grades_variance(scores):
average = grades_average(scores)
variance = 0
for score in scores:
variance += (average - score) ** 2
return variance / len(scores)
32
def grades_std_deviation(variance):
return variance ** 0.5
print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
variance = grades_variance(grades)
print grades_std_deviation(variance)
For each key in my_dict: print out the key , then a space, then the value stored by that key.
EX 3/18:
my_dict = {
"Spaghetti": "Meatballs",
"Reddit": "Computer",
"Sports": "Score"
}
List comprehensions are a powerful way to generate lists using the for/in and if keywords we've
learned.
List comprehension example syntax:
new_list = [x for x in range(1,6)]
# => [1, 2, 3, 4, 5]
This will create a new_list populated by the numbers one to five. If you want those numbers
33
If you only wanted the doubled numbers that are evenly divisible by three:
doubles_by_3 = [x*2 for x in range(1,6) if (x*2)%3 == 0]
# => [6]
Exercise:
cubes_by_four = [x**3 for x in range(1,11) if (x**3) % 4 == 0]
print cubes_by_four
1.
2.
3.
34
to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14]
Adv. Topics 12-13/18 - Anonymous Functions (lambda)
New
Python allows for functional programming (youre allowed to pass functions around just as if they
lambda x: x % 3 == 0
is the same as:
def by_three(x):
return x % 3 == 0
Dont need to actually give the function a name; does its work and returns a value w/o one, which is
Use a list comprehension to create a list, threes_and_fives, that consists only of the numbers
When we count, we usually do it in base 10. That means that each place in a number can hold one
of ten values, 0-9. In binary we count in base two, where each place can hold one of two values: 0 or 1. The
counting pattern is the same as in base 10 except when you carry over to a new column, you have to carry
over every time a place goes higher than one (as opposed to higher than 9 in base 10).
35
For example, the numbers one and zero are the same in base 10 and base 2. But in base 2, once
you get to the number 2 you have to carry over the one, resulting in the representation "10". Adding one
again results in "11" (3) and adding one again results in "100" (4).
Contrary to counting in base 10, where each decimal place represents a power of 10, each place in
a binary number represents a power of two (or a bit). The rightmost bit is the 1's bit (two to the zero power),
the next bit is the 2's bit (two to the first), then 4, 8, 16, 32, and so on.
The binary number '1010' is 10 in base 2 because the 8's bit and the 2's bit are "on":
https://www.youtube.com/watch?v=ry1hpm1GXVI/
can use bin() function to convert base 10 to base 2.
can also use hex() or oct() functions to convert to base 6 or base 8, respectively
int() function can have two parameters; 2nd parameter specifies what base the 1st parameter is in
the int() function will convert the 1st parameter into base 10
Example:
print int("11001001",2)
201
Introduction to Bitwise Operators 6/14 - Shifting a bit
Bitwise shift to the left is like multiplying your binary number by 2,4,8,16 etc depending on how
Shift the variable shift_right to the right twice (>> 2) and shift the variable shift_left to the left
twice (<< 2). Try to guess what the printed output will be!
shift_right = 0b1100
shift_left = 0b1
# Your code here!
shift_right = shift_right >> 2
shift_left = shift_left << 2
print bin(shift_right)
36
print bin(shift_left)
objects - can think of an object as a single data structure that contains data as well as functions
methods - functions of objects
class is just a way of organizing and producing objects with similar attributes and methods
a basic class consists only of the class keyword, the name of the class, and the class from which
37
__init__() function is required for classes, and its used to initialize the objects it creates.
always takes at least one argument, self, that refers to the object being created
__init__() can think of the function that boots up each object that it creates
Remove the pass statement in your class definition, then go ahead and define an __init__()
function for your Animal class. Pass it the argument self for now; we'll explain how this works in greater
detail in the next section. Finally, put the pass into the body of the __init__() definition, since it will expect an
indented block.
class Animal(object):
def __init__(self):
pass
Introduction to Classes 4/18
Overly common to use the word self as the first parameter that runs through __init__(), so you
should use this so other people can understand your code
Python will use the first parameter, in this case self, to refer to the object being created; this is why
it is often called self, since the parameter gives the object its identity
1. Pass __init__() a second parameter,name.
2. In the body of __init__(), let the function know that name refers to the created object's name by
typing self.name = name. (This will become crystal clear in the next section.)
class Animal(object):
def __init__(self, name):
self.name = name
Introduction to Classes 5/18 - Instantiating an Object
can access attributes of our object using dot notation; see below
class Square(object):
def __init__(self):
self.sides = 4
my_shape = Square()
print my_shape.sides
Outside the class definition, we create a new instance of Square named my_shape and access
38
1.
Outside the Animal class definition, create a variable named zebra and set it equal to
Animal("Jeffrey").
2.
Then print out zebra's name.
class Animal(object):
def __init__(self, name):
self.name = name
zebra = Animal("Jeffrey")
print zebra.name
Introduction to Classes 6/18 - More on __init__()
Check out the examples in the editor. See how __init__() "boots up" each object to expect a name
and an age, then uses self.name and self.age to assign those names and ages to each object? Add a third
attribute, is_hungry to __init__(), and click Save & Submit Code to see the results.
# Class definition
class Animal(object):
"""Makes cute animals."""
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry
# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.
zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)
print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry
Introduction to Classes 7/18 - Class Scope
not all variables are accessible to all parts of a Python program at all times
the same goes for functions: some are available everywhere, some are only available to members
of a certain class, and still others are only available to particular instance objects
scope - the context in which its visible to the program
global variables - variables that are available everywhere
member variables - variables that are only available to members of a certain class
instance variables - variables that are only available to members of a certain instance
class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
zebra = Animal("Jeffrey", 2)
39
giraffe = Animal("Bruce", 1)
panda = Animal("Chad", 7)
print zebra.name, zebra.age, zebra.is_alive
print giraffe.name, giraffe.age, giraffe.is_alive
print panda.name, panda.age, panda.is_alive
Note that each individual animal gets its own name and age (since they're all initialized
individually), but they all have access to the member variable is_alive, since they're all members of the
Animal class.
Then, create two new Animals: sloth and ocelot. (Give them whatever names and ages you like.)
3.
Finally, on three separate lines, print out the health of your hippo, sloth, and ocelot.
class Animal(object):
"""Makes cute animals."""
is_alive = True
health = "good"
def __init__(self, name, age):
self.name = name
self.age = age
# Add your method here!
def description(self):
print self.name
print self.age
40
print self.health
hippo = Animal("John", 100)
sloth = Animal("Jack", 200)
ocelot = Animal("Jane", 300)
hippo.description()
print hippo.health
print sloth.health
print ocelot.health
Classes like Animal and Fruit make it easy to understand the concepts of classes and instances,
but you probably won't see many zebras or lemons in real-world programs.
However, classes and objects are often used to model real-world objects. The code in the editor is
a more realistic demonstration of the kind of classes and objects you might find in commercial software.
Here we have a basic ShoppingCart class for creating shopping cart objects for website customers; though
basic, it's similar to what you'd see in a real program.
1. Create an instance of ShoppingCart called my_cart. Initialize it with any values you like, then use
the add_item method to add an item to your cart.
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
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def remove_item(self, product):
"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."
41
my_cart = ShoppingCart("Ryan")
my_cart.add_item("Apples", 10)
42