Learn Python from Codecademy
Jump to navigation
Jump to search
# Reference: http://www.codecademy.com/tracks/python
# Set the variables to the values listed in the instructions
my_int = 7
my_float = 1.23
my_bool = True
print (my_bool)
# =============
def spam():
eggs = 12
return eggs
print (spam())
# ==============
# Comments
"""Here is my commnts
Again yes it is
Really """
# ==============
#Set eggs equal to 100 using exponentiation on line 3!
eggs = 10**2
print (eggs)
#Set spam equal to 1 using modulo on line 3!
spam = 3%2
print (spam)
#
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:
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5
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()
#clinic()
#
# 20 + -10 * 2 > 10 % 3 % 2
bool_one = True if (20 + -10 * 2 > 10 % 3 % 2) else False
# (10 + 17)**2 == 3**6
bool_two = True if ((10 + 17)**2 == 3**6) else False
# 1**2**3 <= -(-(-1))
bool_three = True if (1**2**3 <= -(-(-1))) else False
# 40 / 20 * 4 >= -4**2
bool_four = True if (40 / 20 * 4 >= -4**2) else False
# 100**0.5 != 6 + 4
bool_five = True if(100**0.5 != 6 + 4) else False
# Easter Egg - The Zen of Python
import this
#
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)
# Math
import math
print (math.sqrt(25))
# Or import only sqrt function only
from math import sqrt
print (math.sqrt(25))
# Import *everything* from the math module
from math import *
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)
# Min and Mox
print (max(1, 344, -330))
print (min(1, 344, -330))
print (abs(-54))
# Print Types
print (type(1))
print (type(2.3))
print (type('ab'))
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!'
# ===============================
# List
suitcase = []
suitcase.append("sunglasses")
# Your code here!
suitcase.append("sun")
suitcase.append("glass")
suitcase.append("link")
list_length = len(suitcase)
print ("There are %d items in the suitcase." % list_length)
print (suitcase)
# List Slicing
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
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)
# Replace by index
animals.insert(duck_index, "cobra")
print (animals)
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)
# Key-Pair Values
# 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'])
print (residents['Burmese Python'])
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)
# Another Key-Pair
# 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']
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Jimp'
print (zoo_animals)
# Another Key-Pair
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()
# 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'])
# KEY
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."
}
#
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))
# List Manipulation
n = [1, 3, 5]
# Append the number 4 here
n.append(4)
# Remove the first item in the list here
n.pop(0)
print (n)
# ===================
# Arbitrary number of arguments
m = 5
n = 13
# Add add_function here!
def add_function(*args):
return sum(args)
print (add_function(m, n))
# Flatten the list
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(n):
alist = []
for i in range(len(n)):
alist += n[i]
return alist
print (flatten(n))
# Join an arbitray number of lists
m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]
# Update the below function to take
# an arbitrary number of arguments
m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]
def join_lists(*args):
alist = []
for i in range(len(args)):
alist += args[i]
return alist
print (join_lists(m, n, o))
# ===============================
# Battle Ship Game
from random import randint
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)
# Everything from here on should go in your for loop!
# 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))))
# =======
# Even list
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print (evens_to_50)
# Double value
doubles = [x*2 for x in range(1,6)]
doubles_by_3 = [x*2 for x in range(1,6) if (x*2)%3 == 0]
# =======
# anonymous function
my_list = range(16)
print (filter(lambda x: x % 3 == 0, my_list))
#lambda variable: expression
squares = [x**2 for x in range(1,11)]
print (*filter(lambda x: x>= 30 and x<=70, squares))
# Decode message
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
# -1 text backward
message = garbled[::-1].replace('X','')
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda x: x.replace('X',''), garbled)
print (message)
# Bitwise Operations
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
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
# Your code here!
shift_right = shift_right >> 2
shift_left = shift_left<<2
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))
#
#Just Flip Out
"""
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.
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
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
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()
# Refer to parent or super class
"""
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
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
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)
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)
# ==============
# FILE
my_list = [i**2 for i in range(1,11)]
# 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).
"""
"""
# Open the file for reading
read_file = open("text.txt", "r")
# Use a second file handler to open the file for writing
write_file = open("text.txt", "w")
# Write to the file
write_file.write("Not closing files is VERY BAD.")
write_file.close()
# Try to read from the file
print read_file.read()
read_file.close()
"""
"""
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!")
"""