Index :
Changing the index
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked
#the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[2] = "hyena"
# Changes "sloth" to "hyena"
Late Arrivals & List the Length of the List
suitcase = []
suitcase.append("sunglasses")
# Your code here!
suitcase.append("charger")
suitcase.append("tshirts")
suitcase.append("shorts")
list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase
Output:
There are 4 items in the suitcase.
['sunglasses', 'charger', 'tshirts', 'shorts']
None
Example 2:
letters = ['a', 'b', 'c']
letters.append('d')
print len(letters)
print letters
List Slicing
letters = ['a', 'b', 'c', 'd', 'e']
slice = letters[1:3]
print slice
print letters
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:6] # The last two items (index four and five)
so first = [sunglasses, hat] (exclude position 2)
middle=[passport, laptop]
BUT, the suitcase list elements do not change!
Slicing List & String
my_list[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last items
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
Maintaining Order or Inserting index into a Specific Place
animals = ["ant", "bat", "cat"]
print animals.index("bat")
Output : 1
animals.insert(1, "dog")
print animals
Output: ["ant", "dog", "bat", "cat"]
Instructions:
Use the .index(item) function to find the index of "duck". Assign that result to a variable called duck_index.
Then .insert(index, item) the string "cobra" at that index.
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
animals.insert(duck_index,"cobra")
print animals # Observe what prints after the insert operation
Output:
['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox']
None
For-Loop
my_list = [1,9,3,8,5,7]
for number in my_list:
print 2*number # Your code here
Output: 2, 18, 6, 16, 10, 14
for variable in list_name:
# Do stuff!
For-Loop Sorting & Appending
animals = ["cat", "ant", "bat"]
animals.sort()
for animal in animals:
print animal
Output:
"ant", "bat", "cat"
Example 2:
start_list = [5, 3, 1, 2, 4]
square_list = []
for number in start_list:
square_list.append(number**2)# Your code here!
square_list.sort()
print square_list
Output: [1, 4, 9, 16, 25]
Dictionary – Key
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
key 1, key 2, key 3 = key-value pairs
# 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
# Your code here!
print residents['Sloth']
print residents['Burmese Python']
Output: 105
Output: 106
Dictionary – New Entries
dict_name[new_key] = new_value
An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
# Your code here: Add some dish-price pairs to menu!
menu['Despacito']=19.2
menu['Dog']=20
menu['Cat']=30
print "There are " + str(len(menu)) + " items on the menu."
print menu
output:
14.5
There are 4 items on the menu.
{'Chicken Alfredo': 14.5, 'Despacito': 19.2, 'Dog': 20, 'Cat': 30}
None
Dictionary – Deletion
del dict_name[key_name]
# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
# Your code here!
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin']='Bird'
print zoo_animals
Output: {'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Bird'}
None
Remove stuff from a list
beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
Output -- >> ["john","paul","george","ringo"]
Alternative Algorithm:
dict_name['list_key'].list_function()
Complicating List & Dictionaries
my_dict = {
"fish": ["c", "a", "r", "p"],
"cash": -4483,
"luck": "good"
}
print my_dict["fish"][0]
Output : c
inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Your code here
inventory['pocket']=['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = inventory['gold']+50
print inventory
Output:
{'pocket': ['seashell', 'strange berry', 'lint'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pouch': ['flint', 'gemstone', 'twine'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 550}
None
Re
A Day at Supermarket Case:
for loops allow us to iterate through all of the elements in a list from the left-most (or zeroth element) to the right-most element. A sample loop would be structured as follows:
a = ["List of some sort”]
for x in a:
# Do something for every x
for item in [1, 3, 21]:
print item
would print 1, then 3, and then 21
Example:
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
print name
# A simple dictionary
d = {"foo" : "bar"}
for key in d:
print d[key] # prints "bar"
webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."
}
# Add your code below!
for jargon in webster:
print webster[jargon]
Output:
A star of a popular children's cartoon show.
Goes on the floor.
A small amount.
The sound a goat makes.
None
*Note that the outcome will not come as order using this function.
For-Loop with if-statement
numbers = [1, 3, 4, 7]
for number in numbers:
if number > 6:
print number
print "We printed 7."
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for number in a:
if number%2==0:
print number
List + Function:
def count_small(numbers):
total = 0
for n in numbers:
if n < 10:
total = total + 1
return total
lost = [4, 8, 15, 16, 23, 42]
small = count_small(lost)
print small
fizz_count = ["fizz","cat","fizz"]
def fizz_count(x):
count=0
for item in x:
if item=="fizz":
count=count+1
return count
output: 2
String Looping:
for letter in "Codecademy":
print letter
# Empty lines to make the output pretty
print (but actually this print can be skipped)
print (but actually this print can be skipped)
word = "Programming is fun!"
for letter in word:
# Only print out the letter i
if letter == "i":
print letter
Output:
C
o
d
e
c
a
d
e
m
y
i
i
None
Supermarket Project:
prices={
"banana":4,
"apple":2,
"orange":1.5,
"pear":3
}
stock={
"banana":6,
"apple":0,
"orange":32,
"pear":15
}
for fruit in prices:
print fruit
print "price: %s" % price[fruit]
print "stock: %s" % stock[fruit]
Output:
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
None
for fruit in prices:
dollar_value=prices[fruit]*stock[fruit]
total=total+dollar_value
print total
Output:
117.0
Making a purchasing:
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
n = [1, 2, 5, 10, 13]
print sum(n)
def compute_bill(food):
total=0
for fruit in food:
total+=prices[fruit]
return total
(To sum up all the prices for each fruit together)
def compute_bill(food):
total=0
for fruit in food:
if stock[fruit]>0:
total+=prices[fruit]
stock[fruit]-=1
return total
(To sum up the fruit which in stocks & reduce the inventory after purchasing by 1)
Chapter 6: School Database Case Study
Task:
Create three dictionaries: lloyd, alice, and tyler.
Give each dictionary the keys "name", "homework", "quizzes", and "tests".
Solution:
lloyd={"name":"Lloyd",
"homework":[],
"quizzes":[],
"tests":[]
}
alice={"name":"Alice",
"homework":[],
"quizzes":[],
"tests":[]
}
tyler={"name":"Tyler",
"homework":[],
"quizzes":[],
"tests":[]
}
Task:
To add value into the database
Solution:
lloyd["homework"]=90, 97, 75, 92
lloyd["quizzes"]=88, 40, 94
lloyd["tests"]=75, 90
Task:
Below your code, create a list called students that contains lloyd, alice, and tyler.
Solution:
students=[lloyd,alice,tyler]
Task:
for each student in your students list, print out that student's data, as follows:
Solution:
for student in students:
print student["name"]
print student["homework"]
print student["quizzes"]
print student["tests"]
Output:
Lloyd
(90, 97, 75, 92)
(88, 40, 94)
(75, 90)
Alice
[100.0, 92.0, 98.0, 100.0]
[82.0, 83.0, 91.0]
[89.0, 97.0]
Tyler
[0.0, 87.0, 75.0, 22.0]
[0.0, 75.0, 78.0]
[100.0, 100.0]
None
What is float()?
5 / 2
# 2
5.0 / 2
# 2.5
float(5) / 2
# 2.5
To stay the float(5) can be divided into a decimal place digit
Task:
Write a function average that takes a list of numbers and returns the average.
Solution:
def average(numbers):
total=sum(numbers)
total=float(total)
result=total/len(numbers)
return result
Task:
Write a function called get_averagethat takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average.
Define a function called get_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.
Solution:
def get_average(student):
homework=average(student["homework"])
quizzes=average(student["quizzes"])
tests=average(student["tests"])
return 0.1*homework+0.3*quizzes+0.6*tests
Task:
Define a new function called get_letter_grade that has one argument called score. Expect score to be a number.
Inside your function, test scoreusing a chain of if: / elif: /else: statements, like so:
If score is 90 or above: return "A"
Else if score is 80 or above: return"B"
Else if score is 70 or above: return"C"
Else if score is 60 or above: return"D"
Otherwise: return "F"
Finally, test your function! Call your get_letter_grade function with the result of get_average(lloyd). Print the resulting letter grade.
Solution:
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"
Task:
Define a function called get_class_average that has one argument students. You can expect students to be a list containing your three students.
First, make an empty list called results.
For each student item in the class list, calculate get_average(student) and then call results.append() with that result.
Finally, return the result of calling average() with results.
Solution:
def get_class_average(students=[lloyd,alice,tyler]):
results=[]
for student in students:
ga=get_average(student)
results.append(ga)
return average(results)
return average(results)
Task:
Finally, print out the result of calling get_class_average with your students list. Your studentsshould be [lloyd, alice, tyler].
Then, print the result of get_letter_grade for the class's average.
Solution:
print get_class_average(students=[lloyd,alice,tyler])
print get_letter_grade(get_class_average(students=[lloyd,alice,tyler]))