Learn Python from Codecademy


 * 1) Reference: http://www.codecademy.com/tracks/python

my_int = 7 my_float = 1.23 my_bool = True
 * 1) Set the variables to the values listed in the instructions

print (my_bool)

def spam: eggs = 12 return eggs

print (spam)

"""Here is my commnts Again yes it is Really """
 * 1) Comments
 * 1) Comments

eggs = 10**2 print (eggs)
 * 1) Set eggs equal to 100 using exponentiation on line 3!
 * 1) Set eggs equal to 100 using exponentiation on line 3!

spam = 3%2 print (spam)
 * 1) Set spam equal to 1 using modulo on line 3!

meal = 44.50 tax = 0.0675 tip = 0.15

meal = meal + meal * tax total = meal + meal * tip

print("%.2f" % total)

string_1 = "Camelot" string_2 = "place" print ("Let's not go to %s. 'Tis a silly %s." % (string_1, string_2))

""" The string "PYTHON" has six characters, numbered 0 to 5, as shown below:

+---+---+---+---+---+---+ +---+---+---+---+---+---+ 0   1   2   3   4   5
 * P | Y | T | H | O | N |

So if you wanted "Y", you could just type "PYTHON"[1] (always start counting from 0!) """ fifth_letter = "MONTY"[4] print (fifth_letter)

parrot = "Norwegian Blue" print (parrot.lower) print (parrot.upper)

"""" name = input("What is your name?") quest = input("What is your quest?") color = input("What is your favorite color?")

print ("Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color)) """ from datetime import datetime

now = datetime.now print (now) print (now.month) print (now.day) print (now.year) print (str(now.month) + "/" + str(now.day) + "/" + str(now.year)) print (str(now.hour) + ":" + str(now.minute) + ":" + str(now.second))

def clinic: print ("You've just entered the clinic!") print ("Do you take the door on the left or the right?") answer = input("Type left or right and hit 'Enter'.").lower if answer == "left" or answer == "l": print ("This is the Verbal Abuse Room, you heap of parrot droppings!") elif answer == "right" or answer == "r": print ("Of course this is the Argument Room, I've told you that already!") else: print ("You didn't pick left or right! Try again.") clinic


 * 1) clinic



bool_one = True if (20 + -10 * 2 > 10 % 3 % 2) else False
 * 1) 20 + -10 * 2 > 10 % 3 % 2

bool_two = True if ((10 + 17)**2 == 3**6) else False
 * 1) (10 + 17)**2 == 3**6

bool_three = True if (1**2**3 <= -(-(-1))) else False
 * 1) 1**2**3 <= -(-(-1))

bool_four = True if (40 / 20 * 4 >= -4**2) else False
 * 1) 40 / 20 * 4 >= -4**2

bool_five = True if(100**0.5 != 6 + 4) else False
 * 1) 100**0.5 != 6 + 4

import this
 * 1) Easter Egg - The Zen of Python

def tax(bill): """Adds 8% tax to a restaurant bill.""" bill *= 1.08 print ("With tax: %f" % bill) return bill

def tip(bill): """Adds 15% tip to a restaurant bill.""" bill *= 1.15 print ("With tip: %f" % bill) return bill

meal_cost = 100 meal_with_tax = tax(meal_cost) meal_with_tip = tip(meal_with_tax)

groceries = ["banana", "orange", "apple"]

stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }

prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 }

def compute_bill(food): total = 0 for x in food: if stock[x] > 0: total += prices[x] stock[x] = stock[x] - 1

return total

def square(n): """Returns the square of a number.""" squared = n**2 print ("%d squared is %d." % (n, squared)) return squared

square(10)

def power(base, exponent): # Add your parameters here! result = base**exponent print ("%d to the power of %d is %d." % (base, exponent, result))

power(37,4)


 * 1) Math

import math print (math.sqrt(25)) from math import sqrt print (math.sqrt(25)) from math import *
 * 1) Or import only sqrt function only
 * 1) Import *everything* from the math module

import math           # Imports the math module print (dir(math))      # Prints everything to a list of things from math

def biggest_number(*args): print (max(args)) return max(args)

def smallest_number(*args): print (min(args)) return min(args)

def distance_from_zero(arg): print (abs(arg)) return abs(arg)

biggest_number(-10, -5, 5, 10) smallest_number(-10, -5, 5, 10) distance_from_zero(-10)

print (max(1, 344, -330)) print (min(1, 344, -330)) print (abs(-54))
 * 1) Min and Mox

print (type(1)) print (type(2.3)) print (type('ab'))
 * 1) Print Types

def shut_down(arg): if arg in ('Yes','yes','YES'): print ('Shutting down...') return 'Shutting down...' elif arg in ('No','no','NO'): print ('Shutdown aborted!') return 'Shutdown aborted!' else: print ('Sorry, I didn\'t understand you.') return 'Sorry, I didn\'t understand you.'

def distance_from_zero(arg): if type(arg) in (type(1), type(1.0)): print (abs(arg)) return abs(arg) else: print ('Not an integer or float!') return 'Not an integer or float!'

suitcase = [] suitcase.append("sunglasses")
 * 1) List
 * 1) List

suitcase.append("sun") suitcase.append("glass") suitcase.append("link")
 * 1) Your code here!

list_length = len(suitcase)

print ("There are %d items in the suitcase." % list_length) print (suitcase)

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
 * 1) List Slicing

first =   suitcase[0:2] middle =  suitcase[2:4] last =    suitcase[4:6]

print (first) print (middle) print (last)

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

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck")  # Use index to find "duck" print (duck_index)

animals.insert(duck_index, "cobra") print (animals)
 * 1) Replace by index

start_list = [5, 3, 1, 2, 4] square_list = []

for a in start_list: square_list.append(a**2)

square_list.sort print (square_list)

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print (residents['Puffin']) # Prints Puffin's room number print (residents['Sloth']) print (residents['Burmese Python'])
 * 1) Key-Pair Values
 * 2) Assigning a dictionary with three key-value pairs to residents:

menu = {} # Empty dictionary menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair print (menu['Chicken Alfredo']) menu['Spam'] = 2.50 menu['Cole'] = 1.50 menu['Slaw'] = 6.50 print ("There are " + str(len(menu)) + " items on the menu.") print (menu)

zoo_animals = { 'Unicorn' : 'Cotton Candy House', 'Sloth' : 'Rainforest Exhibit', 'Bengal Tiger' : 'Jungle House', 'Atlantic Puffin' : 'Arctic Exhibit', 'Rockhopper Penguin' : 'Arctic Exhibit'}
 * 1) Another Key-Pair
 * 2) key - animal_name : value - location
 * 1) A dictionary (or list) declaration may break across multiple lines

del zoo_animals['Unicorn'] del zoo_animals['Sloth'] del zoo_animals['Bengal Tiger'] zoo_animals['Rockhopper Penguin'] = 'Jimp' print (zoo_animals)
 * 1) Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)

inventory = {'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
 * 1) Another Key-Pair

inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
 * 1) Adding a key 'burlap bag' and assigning a list to it

inventory['pouch'].sort
 * 1) Sorting the list found under the key 'pouch'
 * 1) Here the dictionary access expression takes the place of a list name

inventory['pocket'] = ['seashell', 'strange berry', 'lint'] inventory['backpack'].sort print (inventory['backpack'])

inventory['backpack'].remove('dagger') print (inventory['backpack'])

inventory['gold'] = inventory['gold']+50 print (inventory['gold'])

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." }
 * 1) KEY

for key in webster: print (key, webster[key])



lloyd = {"name":"Lloyd", "homework":[], "quizzes":[], "tests":[]} alice = {"name":"Alice", "homework":[], "quizzes":[], "tests":[]} tyler = {"name":"Tyler", "homework":[], "quizzes":[], "tests":[]}

lloyd = { "name": "Lloyd", "homework": [90, 97, 75, 92], "quizzes": [88, 40, 94], "tests": [75, 90] } alice = { "name": "Alice", "homework": [100,92,98,100], "quizzes": [82,83,91], "tests": [89,97] } tyler = { "name": "Tyler", "homework": [0,87,75,22], "quizzes": [0,75,78], "tests": [100,100] }

students = [lloyd,alice,tyler]

for s in students: print (s["name"]) print (s["homework"]) print (s["quizzes"]) print (s["tests"])

def average(alist): return sum(alist)/float(len(alist))

def get_average(astudent): avg_homework = average(astudent["homework"]) avg_quizzes = average(astudent["quizzes"]) avg_tests = average(astudent["tests"]) return avg_homework*0.10 + avg_quizzes*0.30 + avg_tests*0.60

def get_letter_grade(ascore): #ascore = round(ascore) if ascore >= 90.0: return "A" elif ascore >= 80.0: return "B" elif ascore >= 70.0: return "C" elif ascore >= 60.0: return "D" else: return "F"

def get_class_average(students): avg = 0 for s in students: avg += get_average(s)

return avg/len(students)

students = [lloyd, alice, tyler]

for s in students: print (get_letter_grade(get_average(s)))

print (get_class_average(students))

n = [1, 3, 5]
 * 1) List Manipulation

n.append(4)
 * 1) Append the number 4 here

n.pop(0)
 * 1) Remove the first item in the list here

print (n)


 * 1) Arbitrary number of arguments
 * 1) Arbitrary number of arguments

m = 5 n = 13 def add_function(*args): return sum(args)
 * 1) Add add_function here!

print (add_function(m, n))

n = 1, 2, 3], [4, 5, 6, 7, 8, 9
 * 1) Flatten the list
 * 1) Add your function here

def flatten(n): alist = [] for i in range(len(n)): alist += n[i] return alist

print (flatten(n))

m = [1, 2, 3] n = [4, 5, 6] o = [7, 8, 9]
 * 1) Join an arbitray number of lists

m = [1, 2, 3] n = [4, 5, 6] o = [7, 8, 9]
 * 1) Update the below function to take
 * 2) an arbitrary number of arguments

def join_lists(*args): alist = [] for i in range(len(args)): alist += args[i] return alist

print (join_lists(m, n, o))

from random import randint
 * 1) Battle Ship Game
 * 1) Battle Ship Game

board = []

for x in range(5): board.append(["O"] * 5)

def print_board(board): for row in board: print (" ".join(row))

print ("Let's play Battleship!") print_board(board)

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)


 * 1) Everything from here on should go in your for loop!
 * 2) Be sure to indent four spaces!

for turn in range(1): #guess_row = int(input("Guess Row:")) guess_row = 1 #guess_col = int(input("Guess Col:")) guess_col = 1

if guess_row == ship_row and guess_col == ship_col: print ("Congratulations! You sunk my battleship!") break else: if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print ("Oops, that's not even in the ocean.") elif(board[guess_row][guess_col] == "X"): print ("You guessed that one already.") else: print ("You missed my battleship!") if turn == 3: print ("Game Over") board[guess_row][guess_col] = "X" # Print (turn + 1) here! print (turn+1) print_board(board)

"""enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence. It's very similar to using a normal for loop with a list, except this gives us an easy way to count how many items we've seen so far. """ choices = ['pizza', 'pasta', 'salad', 'nachos']

print ('Your choices are:') for index, item in enumerate(choices): print (index+1, item)

""" Multiple lists

It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.

zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.

zip can handle three or more lists as well! """ list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b): # Add your code here! if a >= b:       print (a) else: print (b)

""" For / else

Just like with while, for loops may have an else associated with them.

In this case, the else statement is executed after the for, but only if the for ends normallyâ€”that is, not with a break. This code will break when it hits 'tomato', so the else block won't be executed. """ fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print ('You have...') for f in fruits: if f == 'tomato': print ('A tomato is not a fruit!') # (It actually is.) break print ('A', f) else: print ('A fine selection of fruits!')

print (round(-3.4))

import math grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

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 / len(grades) return average

def grades_variance(scores, avg): variance = 0 for s in scores: variance += (s-avg)**2

return variance/len(scores)

print (grades_variance(grades, grades_average(grades)))

def grades_std_deviation(variance): return math.sqrt(variance)

print (grades_std_deviation(grades_variance(grades, grades_average(grades))))

evens_to_50 = [i for i in range(51) if i % 2 == 0] print (evens_to_50)
 * 1) Even list
 * 1) Even list

doubles = [x*2 for x in range(1,6)]
 * 1) Double value

doubles_by_3 = [x*2 for x in range(1,6) if (x*2)%3 == 0]

my_list = range(16) print (filter(lambda x: x % 3 == 0, my_list))
 * 1) anonymous function
 * 1) anonymous function

squares = [x**2 for x in range(1,11)] print (*filter(lambda x: x>= 30 and x<=70, squares))
 * 1) lambda variable: expression

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI" message = garbled[::-1].replace('X','')
 * 1) Decode message
 * 1) -1 text backward

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" message = filter(lambda x: x.replace('X',''), garbled) print (message)

print (5 >> 4) # Right Shift print (5 << 1) # Left Shift print (8 & 5)  # Bitwise AND print (9 | 4)  # Bitwise OR print (12 ^ 42) # Bitwise XOR print (~88)    # Bitwise NOT
 * 1) Bitwise Operations

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) print (0b11 * 0b11)

one = 0b1 two = 0b10 three = 0b11 four = 0b100 five = 0b101 six = 0b110 seven = 0b111 eight = 0b1000 nine = 0b1001 ten = 0b1010 eleven = 0b1011 twelve = 0b1100

bin(1) hex(2) oct(3) 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))

""" Left Bit Shift (<<) 0b000001 << 2 = 0b000100 (1 << 2 = 4) 0b000101 << 3 = 0b101000 (5 << 3 = 40)

Right Bit Shift (>>) 0b0010100 >> 3 = 0b000010 (20 >> 3 = 2) 0b0000010 >> 2 = 0b000000 (2 >> 2 = 0) """

shift_right = 0b1100 shift_left = 0b1

shift_right = shift_right >> 2 shift_left = shift_left<<2
 * 1) Your code here!

print (bin(shift_right)) print (bin(shift_left))

"""    a:   00101010   42     b:   00001111   15

=
====== a & b:  00001010   10

a:  00101010   42 b:  00001111   15

=
====== a & b:  00001010   10

a: 00101010   42 b: 00001111   15

=
=== a ^ b: 00100101   37

NOT print ~1 print ~2 print ~3 print ~42 print ~123 """

def check_bit4(n): mask = 0b1000 if (n & 0b1000) > 0: return "on" else: return "off"

check_bit4(0b1) # ==> "off" check_bit4(0b11011) # ==> "on" check_bit4(0b1010) #

a = 0b10111011 mask = 0b100 print (bin(a | mask))

""" Using the XOR (^) operator is very useful for flipping bits. Using ^ on a bit with the number one will return a result where that bit is flipped.
 * 1) Just Flip Out
 * 1) Just Flip Out

For example, let's say I want to flip all of the bits in a. I might do this:

a = 0b110 # 6 mask = 0b111 # 7 desired = a ^ mask # 0b

Slip and Slide

a = 0b101 mask = (0b1 << 9) # One less than ten desired = a ^ mask

"""

class Fruit(object): """A class that makes various tasty fruits.""" def __init__(self, name, color, flavor, poisonous): self.name = name self.color = color self.flavor = flavor self.poisonous = poisonous
 * 1) CLASS
 * 1) CLASS

def description(self): print ("I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor))

def is_edible(self): if not self.poisonous: print ("Yep! I'm edible.") else: print ("Don't eat me! I am super poisonous.")

lemon = Fruit("lemon", "yellow", "sour", False)

lemon.description lemon.is_edible

""" class DerivedClass(Base):  def some_method(self):       super(DerivedClass, self).meth """ class Employee(object): """Models real-life employees!""" def __init__(self, employee_name): self.employee_name = employee_name
 * 1) Refer to parent or super class

def calculate_wage(self, hours): self.hours = hours return hours * 20.00

class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours * 12.00 def full_time_wage(self, hours): return super(PartTimeEmployee, self).calculate_wage(hours)
 * 1) Add your code below!

milton = PartTimeEmployee("Milton") print (milton.full_time_wage(10))

class Point3D(object): def __init__(self, x, y, z): self.x = x       self.y = y        self.z = z    def __repr__(self): return "("+str(self.x)+", "+str(self.y)+", "+str(self.z)+")"

my_point = Point3D(1,2,3) print (my_point)

my_list = [i**2 for i in range(1,11)]
 * 1) FILE
 * 1) FILE
 * 1) Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w")

for item in my_list: f.write(str(item) + "\n")

f.close

""" You can open files in write-only mode ("w"), read-only mode ("r"), read and write mode ("r+"), and append mode ("a", which adds any new data you write to the file to the end of the file). """ """ read_file = open("text.txt", "r")
 * 1) Open the file for reading

write_file = open("text.txt", "w") write_file.write("Not closing files is VERY BAD.")
 * 1) Use a second file handler to open the file for writing
 * 1) Write to the file

write_file.close

print read_file.read read_file.close
 * 1) Try to read from the file

""" """ You may not know this, but file objects contain a special pair of built-in methods: __enter__ and __exit__.

The details aren't important, but what is important is that when a file object's __exit__ method is invoked, it automatically closes the file. How do we invoke this method? With with and as.

The syntax looks like this:

with open("file", "mode") as variable: # Read or write to the file

with open("text.txt", "w") as textfile: textfile.write("Success!")

"""