Resolution for CodeAcademy’s Python exercises

This is a general view from what I practiced at Codecademy Website. The first command they train is related to print a message for strings using comillas:

print "Hello World in HD!"

The next topic is focused in variables, in order to set them, just use the equal sign “=” :

HD = 5
anotherHD = 1.45

This means that HD has the value of 5. And you can test it by typing HD in your prompt. Other kind of variable are booleans, in this case we can assign H as yes and D as no:

H = True
D = False

What if I do print hd, do you think that value is 5? well try it!… it is a sensitive code, so use uppercase or lowercase as your convenience. In this case I am going to change the value:

HD = 3

so, if I type print HD, the answer must be 3 and not 5 as it was set before.


The reserve word to define a function is def, and the rest must be indented with 4 spaces:

def HD():
    x = 12
    return x

print HD()

Any time you want to add a comment in only one line, use the symbol #; if there are more lines, use ”’ at the beginning and at the ending of the comment. To do math, use the operator as you require:

# Set sum equal to the sum of two big numbers
sum = 2355342342354 + 423435465767868

print sum

#Set eggs equal to 100 using exponentiation on line 3!
expo_use = 10 ** 2

print expo_use

#Set spam equal to 1 using modulo on line 3!
spam = 6 % 5

print spam

# this is my first program
monty = True

python = 1.234

monty_python = python ** 2

In order to pay a meal in a restaurant, we set values as tax and tip to calculate the total:

# Assign the variable total on line 8!
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal + meal * tax
total = meal + meal * tip
print("%.2f" % total)

Then, the string lesson shows concatenating strings that can set numbers between comillas. In the next lines we can set the variable message twice and the use of ” \ ” before ” ‘ ” because it could be interpreted as comillas that break the message. Or you can use ” ‘ ” between a message which starts with double comillas ” ” “.

number = '6'
message = "Hello" + number
new_message = 'This isn\'t an example with style!'
allowed_message = "It's not bad to use the simple one."

To work with lists or arrays and strings, do not forget the comillas and start to count from zero instead of one, e.g. if somebody ask for the four letter of GNOME, the answer must be

four_letter = "GNOME"[3]
print four_letter

String methods is the next topic covered and the common are len(), lower(), upper(), str().

project = "GNOME"
pi = 3.1416
print len(project)
print project.lower()
print project.upper()
print str(pi)   #explicit string conversion

To string formatting with % can be used after enter a value from a prompt and store as:

name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_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)

To print the current time of the system, call the library datetime and store in variable like:

from datetime import datetime
now =

print '%s/%s/%s %s:%s:%s' % (now.month,, now.year, now.hour, now.minute, now.second)

Control flow

def guessing():
 print "We are going to guess the number you enter"
 print "Natural numbers are going to use for this exercises"
 answer = raw_input("Type a larger number of one cipher and hit 'Enter'.").lower()
 if answer == "9" or answer == "nine":
    print "Ahhh! the number you typed is nine!"
 elif answer == "8" or answer == "eight":
    print "Ahhh! the number you typed is eight!"
    print "You didn't pick a big number of one cipher."


The use of operators and boleeans can be mixed as follow:

bool_one = 2**3 == 108 % 100 or 'Cleese' == 'King Arthur'
bool_two = not not False
bool_three = 100**0.5 >= 50 or False
bool_four = True and True
bool_five = not 1**100 == 100**1 and 3 * 2 * 1 != 3 + 2 + 1

The reserve word “return” is important to return a value from a function as its indentation:

def using_control_once():
 if True:
    return "Success #1"

def using_control_again():
 if True:
    return "Success #2"

print using_control_once()
print using_control_again()

More uses of conditionals with strings comparison:

answer = "'Tis but a scratch!"

def black_knight():
 if answer == "'Tis but a scratch!":
     return True
     return False # Make sure this returns False

def french_soldier():
 if answer == "Go away, or I shall taunt you a second time!":
     return True
     return False # Make sure this returns False

More uses of conditionals with number comparison:

def greater_less_equal_5(answer):
 if answer > 5:
    return 1
 elif answer < 5: 
    return -1
    return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

Mor conditional uses:

def the_flying_circus():
 if True and True: # Start coding here!
      return True 
 elif 2 > 4:
      return False 
     print "Not 2"
print the_flying_circus()

The answer of Pig Latin is a language game, where you move the first letter of the word to the end and add “ay.” So “Python” becomes “ythonpay.”:

pyg = 'ay'
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
new_word = word[1:len(new_word)] + first + pyg
if len(original) > 0 and original.isalpha():
 print new_word 
 print 'empty'

Defining parameters in functions:

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) # Add your arguments here!

calling function inside another function

def one_good_turn(n):
    return n + 1
def deserves_another(n):
    return one_good_turn(n) + 2

Defining a function of cube and validation of the number divided by 3:

def cube(number):
 return number*number*number
def by_three(number):
    if number % 3 == 0:
         return cube(number)
        return False

Using import

# Ask Python to print sqrt(25) on line 3.
import math
print math.sqrt(25)

just to import function from a module

from math import sqrt
# Import *everything* from the math module on line 3!
from math import *

to see all the functions

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


# Set maximum to the max value of any set of numbers on line 3!
maximum = max(4,5,6)
print maximum


absolute = abs(-42)
print absolute


# Print out the types of an integer, a float,
# and a string on separate lines below.
print type(45)
print type(6.7)
print type("hi")

Function that validate shut down message

def shut_down(s): 
 if s == "yes": 
    return "Shutting down"
 elif s == "no":
    return "Shutdown aborted"
    return "Sorry"

Using the sort function

from math import sqrt
print sqrt(13689)

from math import *

def distance_from_zero(n):
 if type(n) == int or type(n) == float:
    return abs(n)
    return "Nope"

You can define a function to return a value:

def answer():
 return 42

Taking a vacation quiz:

def hotel_cost(nights):
 return 140 * nights

def plane_ride_cost(city):
 if city == "Charlotte":
    return 183
 elif city == "Tampa":
    return 220
 elif city == "Pittsburgh":
    return 222
 elif city == "Los Angeles":
    return 475
def rental_car_cost(days):
 total = 40 * days
 if days >= 7:
    total = total - 50
 elif days >= 3:
    total = total - 20
 return total
def trip_cost(city,days,spending_money):
 return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) + spending_money

print trip_cost("Los Angeles",5,600)

using lists

numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
print numbers[1] + numbers[3]

append function to add items at the end of a list

suitcase = [] 
list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase

accessing to items in a list

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)

Accessing to indexes in a list

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

More about index lists

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
print animals # Observe what prints after the insert operation

Loop and lists:

my_list = [1,2,3,4,5]
for number in my_list:
   print 2 * number

Math function, loop and list

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

for number in start_list:
 square_list.append(number ** 2)
print square_list

The use of a dictionary

# 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']

deleting a value from a dictionary:

# 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'}

del zoo_animals['Unicorn']
del zoo_animals['Sloth']# Your code here!
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Peru'

print zoo_animals

to remove ‘dagger’ from backpack

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']

using dictionary and lists inside dictionary

inventory = {
 'gold' : 500,
 'pouch':['flint','twine','gemstone'], # Assigned a new list
 '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['pocket'] = ['seashell','strange berry','lint']
inventory['gold'] = 500 +50


Using for loop for printing item in a list:

names = ["Adam","Alex","Mariah","Martine","Columbus"]
for each_name in names:
  print each_name

Printing items from a dictionary

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 n in webster: 
   print webster[n]

To print even numbers:

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

Counting items in a list defined as an input in a function

def fizz_count(x):
  count = 0
  for item in x:
    if item == "fizz":
       count = count + 1
return count 

Codeacademy dictionary:

for letter in "Codecademy":
 print letter
# Empty lines to make the output pretty
word = "Programming is fun!"
for letter in word:
 # Only print out the letter i
 if letter == "i":
    print letter

A Day at the Supermarket resolution:

prices = {
 "banana" : 4,
 "apple" : 2,
 "orange" : 1.5,
 "pear" : 3,
stock = {
 "banana" : 6,
 "apple" : 0,
 "orange" : 32,
 "pear" : 15,
total = 0
for key in prices:
 print key
 print "price: %s" % prices[key]
 print "stock: %s" % stock[key]
 total = total + prices[key] * stock[key]
 print "total %s" % total[key]

Stocking out – A Day at the supermarket

shopping_list = ["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 item in food:
    if stock[item] > 0:
       total += prices[item]
       stock[item] -= 1
  return total

Put it Together = Student becomes a teacher

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 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 0.10 * homework + 0.30 * quizzes + 0.60 * tests
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"
     return "F"

def get_class_average(students):
 results = []
 for student in students:
 return average(results)

students = [lloyd,alice,tyler]
print get_class_average(students)
print get_letter_grade(get_class_average(students))

Defining a function that add numbers

m = 5
n = 13
def add_function(x,y):
 return x + y
print add_function(m, n)

String in fucntions

n = "Hello"
def string_function(s):
 return s+"world"
print string_function(n)

Passing a list as argument in a function

def list_function(x):
  return x
n = [3, 5, 7]
print list_function(n)

Using an element from a list in a function

def list_function(x):
 return x[1]
n = [3, 5, 7]
print list_function(n)

Modifying an element of a list in a function

def list_function(x):
  x[1] = x[1] + 3
  return x
n = [3, 5, 7]
print n

List manipulation in functions

n = [3, 5, 7]
def list_extender(lst):
  return lst
print list_extender(n)

Printing out a list item by item in a function

n = [3, 5, 7]
def print_list(x):
   for i in range(0, len(x)):
      print x[i]

Modifying each element in a list in a function

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)

Passing a range into a function

def my_function(x):
   for i in range(0, len(x)):
     x[i] = x[i] * 2
   return x
print my_function(range(0,len(n)))

Iterating over a list in a function

n = [3, 5, 7]
def total(numbers):
  result = 0
  for number in numbers:
    result +=number
  return result
print total(n)

Using strings in lists in functions

n = ["Michael", "Lieberman"]
def join_strings(words):
  result = "" 
  for i in words:
     result += i
  return result
print join_strings(n)

Using two lists as two arguments in a function

m = [1, 2, 3]
n = [4, 5, 6]

def join_lists(x,y):
 return x+y

print join_lists(m, n)
# You want this to print [1, 2, 3, 4, 5, 6]

Using a list of lists in a function

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
   results = []
   for item in lists:
      for n in item:
   return results
print flatten(n)


from random import randint

board = []

for x in range(0,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

for turn in range(4):
 guess_row = int(raw_input("Guess Row:"))
 guess_col = int(raw_input("Guess Col:"))

 if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sunk my battleship!"
    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."
       print "You missed my battleship!"
       board[guess_row][guess_col] = "X"
  print "Turn", turn
  print "Turn", turn + 1
  if turn == 3:
    print "Game Over"


“While you’re” prints 1 message from the if condition and 10 from the while-loop:

count = 0
if count < 10:
  print "Hello, I am an if statement and count is", count
while count < 10:
  print "Hello, I am a while and count is", count
  count += 1

Condition.- if it is not compared with something else, it is assumed that is True by default:

loop_condition = True
while loop_condition:
   print "I am a loop"
   loop_condition = False

“While you’re at it” creates a loop that prints out all the numbers from 1 to 10 squared

num = 1
while num < 11: # Fill in the condition
   print num ** 2 # Print num squared
   num += 1 # Increment num (make sure to do this!)

“Simple errors” checks user input to see if it is valid

choice = raw_input('Enjoying the course? (y/n)')
while choice not in 'y' and  choice not in 'n': 
  choice = raw_input("Sorry, I didn't catch that. Enter again: ")

“Infinite loops” usually occurs if the condition never gets False or bad use of the counter

count = 0
while count < 10: # Add a colon
  print count
  count += 1# Increment count


count = 0
while True:
  print count
  count += 1
  if count >= 10:

“While / else”.- the else block will execute anytime the loop condition is evaluated to False

import random
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"
count = 0
while count < 3:
   num = random.randint(1, 6)
   print num
   if num == 5:
     print "Sorry, you lose!"
     count += 1
   print "You win!"

“Your own while / else” allows the user to guess what the number is three times:

from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
while guesses_left > 0:
  guess = int(raw_input("Please write your guess:"))
  if guess == random_number:
    print "You win"
  guesses_left -= 1
  print "You lose"

“For your health”: Make the loop print the numbers from 0 to 19

print "Counting..."
for i in range(20):
 print i

“For your hobbies” asks for three hobbies and store them in a list called hobbies:

hobbies = []
for i in range(3):
   h = raw_input("Write your hobby:")
print hobbies

“For your strings” means that “for each character c in thing, print c“.

thing = "spam!"
for c in thing:
  print c

word = "eggs!"
for c in word:
  print c

“For your A”, if char is an 'A' or char is an 'a'print 'X', instead of char.

phrase = "A bird in the hand..."
for char in phrase:
  if char == "A" or char == "a":
    print "X" ,
    print char ,
#Don't delete this print statement!

“For your lists” loops that goes through the numbers list and prints each element squared

numbers = [7, 9, 12, 54, 99]
print "This list contains: "
for num in numbers:
  print num
# Add your loop below!
for num in numbers:
  print num ** 2

“Looping over a dictionary” prints the key, followed by the value associated with that key.

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
  print key + " " + d[key]

“Counting as you go”, enumerate works by supplying a corresponding index to each element in the list that you pass it:

choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
   print index+1, item

“Multiple lists” compares 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]
for a, b in zip(list_a, list_b):
  if a > b:
    print a
    print b

“For / else” 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.)
        print 'A', f
        print 'A fine selection of fruits!'

“Change it up” will finish to scan the rest of the list until showing the last message:

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.)
    print 'A', f
    print 'A fine selection of fruits!'

“Create your own”  builds your for/else statement in the editor.

message = "GNOME is an easy and elegant desktop environment"
for char in message:
  if char == 'e' or char == 'E':
    print "3",
    print char,
 print "That's All I Have To Say About That"

“Practice! Practice Practice!” the more you practice, the more you learn

“is_even”, if a number is divided by 2, is an even number:

def is_even(x):
  if x % 2 == 0:
    return True
    return False

“is_int” , a number with a decimal part that is all 0s is also an integer, such as 7.0.

def is_int(x):
  if type(x) == int or x == round(x):
     print True
     print False

“digit_sum” takes a positive integer n as input and returns the sum of all its numbers

def digit_sum(n):
   number = str(n)
   c = 0
   for num in number:
      c = c + int(num)
   print c

Calculate the factorial of a non-negative integer x multiply all the integers from 1 through x

def factorial(x):
 fact = 1
 for i in range(x):
    fact = fact * (i+1)
 print fact

“is_prime” if there is a number between 1 and xthat goes in evenly, then x is not prime.

def is_prime(x):
   if x < 2:
      return False
      for n in range(2,x):
        if x % n == 0:
         return False
      return True

Define a function called "reverse" that takes a string textand returns that string in reverse

def reverse(text):
    for i in text:
    print rev

“anti_vowel” prints the original message without any vowel that the message has.

def anti_vowel(text):
  newtext = ''
  for c in text:
     if c.lower() not in "aeiou":
         newtext += c
  return newtext

“Scrabble” the word "abc" would score 7 points due to the sum of the letters: 3 + 3 + 1:

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
 "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
 "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
 "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
 "x": 8, "z": 10}

def scrabble_score(word):
 sum = 0
 for i in word.lower():
    sum = sum + score[i]
 return sum

“censor” takes two strings, text and word, as input. It should return the text with the wordyou chose replaced with asterisks.

def censor(text,word):
  for i in range(len(words)):
    if words[i]==word:
      words[i]="*" * len(words[i])
  return " ".join(words)

“count” returns the number of times the item occurs in the list.

def count(sequence,item):
  c = 0
  for i in range(len(sequence)):
     if sequence[i] == item:
       c += 1
  return c

“purify” takes in a list of numbers, removes all odd numbers in the list:

def purify(l):
  n = []
  for i in l:
     if i % 2 == 0: n.append(i)
  return n

“product” takes a list of integers as input and returns the product of all of the elements

def product(list_int):
  prod = 1
  for i in list_int:
     prod = prod * i
  return prod

“remove_duplicates” takes in a list and removes elements of the list that are the same

def remove_duplicates(lists):
  comp_list = [ ]
  for i in lists:
     if i not in comp_list:
  return comp_list

“median” takes a list as an input and returns the median value of the list.

def median(lista):
     if len(lista) % 2 == 0:
       print (lista[len(lista)/2]+lista[len(lista)/2 -1])/2.0
       print lista[len(lista)/2]

“Exam Statistics”

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 / float(len(grades))
   return average
def grades_variance(scores):
  average = grades_average(scores)
  variance = 0
  for score in scores:
     variance = variance + (average - score) ** 2
  return variance/len(scores)

def grades_std_deviation(variance):
  return variance ** 0.5
  variance = grades_variance(grades)

print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(variance)

keys() and values() returns an array of tuples with each tuple consisting of a key/value pair

my_dict = {
 "name": "Sandryta",
 "age": 26,
 "status": "single"
print my_dict.keys()
print my_dict.values()

“List Comprehension Syntax” uses a list comprehension to build a list called even_squares

doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]
# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,11) if (x % 2) == 0]
print even_squares

“Now You Try!” uses a list comprehension to create a list, cubes_by_four.

cubes_by_four = [x**3 for x in range(1,11) if (x**3 % 4) == 0]
print cubes_by_four

“Omitting Indices” uses list slicing to print out every odd element from start to finish.

my_list = range(1, 11) # List of numbers 1 - 10
# Add your code below!
print my_list[::2]

“Reversing a List” A negative stride progresses through the list from right to left.

my_list = range(1, 11)
backwards = my_list[::-1]
print backwards

“Stride Length” shows the result of going backwards through to_one_hundred by tens.

to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens

“Practice Makes Perfect” creates a to_21, that’s just the numbers from 1 to 21, inclusive; second list, odds, that contains only the odd numbers in the to_21 list (1, 3, 5, and so on); third list, middle_third, that’s equal to the middle third of to_21, from 8 to 14, inclusive.

to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14]

“Lambda Syntax”  The lambdashould ensure that only "Python" is returned by the filter.

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x:x=="Python", languages)

“Try It!” prints out only the squares that are between 30 and 70 (inclusive).

squares = [x**2 for x in range(1,11)]
print filter(lambda x: x in range(30,71), squares)

“Iterating Over Dictionaries” calls a method such that it will print out all the items

movies = {
 "Monty Python and the Holy Grail": "Great",
 "Monty Python's Life of Brian": "Good",
 "Monty Python's Meaning of Life": "Okay"
print movies.items()

“Comprehending Comprehensions” consists only of the numbers between 1 and 15 (inclusive) that are evenly divisible by 3 or 5.

threes_and_fives=[x for x in range(1,16) if x%3 == 0 or x % 5 == 0]

“List Slicing” our message is backwards, and the letter we want is every other letter than X

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]
print message

“Lambda Expressions” Create a variable called message and set it to the result of calling filter() with the appropriate lambda that will filter out the X. The 2nd argument:garbled.

message = filter(lambda x: x!="X", garbled)
print message

“Just a Little BIT” Bitwise operations are operations that directly manipulate bits. I

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

We can evaluate the first example by setting 5 as 00000101 and then we have to move four positions to the right and then we have 00000000, so the answer is zero.

“Lesson I0: The Base 2 Number System” we can print binary numbers by starting 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
print 0b11 * 0b11

“I Can Count to 1100!” Fill out the numbers with their corresponding binary values up to12

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

“The bin() Function” prints out the binary representations of the numbers 2 through 5:

print bin(1)
print bin(2)
print bin(3)
print bin(4)
print bin(5)

“int()’s Second Parameter”  use int to print the base 10 equivalent of the binary number 11001001. The output for the following code is: 1 2 7 4 5 201

print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
# Print out the decimal equivalent of the binary 11001001.
print int("11001001",2)

“Slide to the Left! Slide to the Right!” shifts the variable shift_right to the right twice (>> 2) and shift the variable shift_left to the left twice (<< 2).

shift_right = 0b1100
shift_left = 0b1
shift_right = shift_right >> 2
shift_left = shift_left << 2
print bin(shift_right)
print bin(shift_left)

“A BIT of This AND That” prints ob100

print bin(0b1110 & 0b101)

“A BIT of This OR That” prints out the result of using | on 0b1110 and 0b101 as a binary str

print bin(0b1110|0b101)

“This XOR That?” prints the result of using ^on 0b1110 and 0b101 as a binary string.

print bin(0b1110 ^ 0b101)

See? This is NOT That Hard! it will print the next number as it is the negation of the num

print ~1
print ~2
print ~3
print ~42
print ~123

“The Man Behind the Bit Mask”  check_bit4, with one argument, input, an integer.

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

“Turn It On” uses a bitmask and the value a in order to achieve a result where the third bit from the right of a is turned on.

a = 0b10111011
mask = 0b110
desired = a | mask
print bin(desired)

“Slip and Slide” flips the nth bit (with the ones bit being the first bit) and store it in result

def flip_bit(number,n):
  mask = 0b1 << n -1
  result = number ^ mask
  return bin(result)

“Why Use Classes?”

class Fruit(object):
 """A class that makes various tasty fruits."""
   def __init__(self, name, color, flavor, poisonous): = 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.flavor)

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

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

“Class Animal Syntax” creates a class called Animal in the editor

# Class definition
class Animal(object):
 """Makes cute animals."""
 # For initializing our instance objects
 def __init__(self, name, age, is_hungry): = 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.age, zebra.is_hungry
print, giraffe.age, giraffe.is_hungry
print, panda.age, panda.is_hungry

“A Methodical Approach” adds a method, description, to your Animal class. Using two separate printstatements, it should print out the nameand age of the animal.

class Animal(object):
 """Makes cute animals."""
 is_alive = True
 def __init__(self, name, age): = name
    self.age = age
 # Add your method here!
 def description(self):
    print "%s" %(
    print "%d" %(self.age)
hippo = Animal("Baloo",43)

“They’re Multiplying!” adds a second member variable called health that contains the string "good"; creates two new Animalssloth and ocelot; and prints their health:

class Animal(object):

 is_alive = True
 health ="good"

 def __init__(self, name, age): = name
    self.age = age

 def description(self):
    print "%s" %(
    print "%d" %(self.age)
hippo = Animal("Baloo",43)
sloth = Animal("Mona",34)
ocelot = Animal("Walter",45)



“It’s Not All Animals and Fruits” creates an instance of ShoppingCartcalled my_cart. Initialize it with any values you like, then use the add_itemmethod to add it 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."
    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."
    print product + " is not in the cart."

my_cart = ShoppingCart("Manzana")
print my_cart.add_item("verde",123)

“Warning: Here Be Dragons”

class Customer(object):
 """Produces objects that represent customers."""
  def __init__(self, customer_id):
     self.customer_id = customer_id
  def display_cart(self):
     print "I'm a string that stands in for the contents of your shopping cart!"

class ReturningCustomer(Customer):
 """For customers of the repeat variety."""
  def display_order_history(self):
     print "I'm a string that stands in for your order history!"

monty_python = ReturningCustomer("ID: 12345")

“Inheritance Syntax” inside the Triangle class, write an __init__() function that takes four arguments: selfside1side2, and side3.

class Shape(object):
 """Makes shapes!"""
  def __init__(self, number_of_sides):
    self.number_of_sides = number_of_sides

class Triangle(Shape):
  def __init__(self, side1, side2, side3):
    self.side1 = side1
    self.side2 = side2
    self.side3 = side3

“Override!” creates a new class PartTimeEmployee and calculate_wage method that overrides Employee‘s

class Employee(object):
  def __init__(self, employee_name):
    self.employee_name = employee_name

  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

“This Looks Like a Job For…” adds a new method called full_time_wage with the arguments self and hours. That method should return the result of a super call to the calculate_wage method of PartTimeEmployee‘s parent class.

class Employee(object):

  def __init__(self, employee_name):
    self.employee_name = employee_name
  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)

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

“Class Basics” Create a class, Triangle. Its __init__()method should take selfangle1angle2, and angle3 as arguments.

class Triangle(object):
 number_of_sides = 3
 def __init__(self, angle1, angle2, angle3):
 self.angle1 = angle1
 self.angle2 = angle2
 self.angle3 = angle3

“Class It Up” creates a method named check_angles. The sum of the angles should return True if the sum of self.angle1self.angle2, and self.angle3 is equal 180, or False.

class Triangle(object):
 number_of_sides = 3
 def __init__(self, angle1, angle2, angle3):
 self.angle1 = angle1
 self.angle2 = angle2
 self.angle3 = angle3
 def check_angles(self):
 if self.angle1 + self.angle2 + self.angle3 == 180:
 return True
 return False

“Instantiate an Object” creates a variable named my_triangleand set it equal to a new instance of your Triangle class. Pass it three angles that sum to 180 (e.g. 90, 30, 60).

class Triangle(object):
 number_of_sides = 3
 def __init__(self, angle1, angle2, angle3):
   self.angle1 = angle1
   self.angle2 = angle2
   self.angle3 = angle3
 def check_angles(self):
   if self.angle1 + self.angle2 + self.angle3 == 180:
     return True
     return False
my_triangle = Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

“Inheritance” creates a class named Equilateralthat inherits from Triangle.

class Triangle(object):
 number_of_sides = 3
 def __init__(self, angle1, angle2, angle3):
   self.angle1 = angle1
   self.angle2 = angle2
   self.angle3 = angle3
 def check_angles(self):
   if self.angle1 + self.angle2 + self.angle3 == 180:
     return True
     return False
class Equilateral(Triangle):
 angle = 60
 def __init__(self):
   self.angle1 = self.angle
   self.angle2 = self.angle
   self.angle3 = self.angle
my_triangle = Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

“Class basics”  defines a new class named “Car” and put something inside the class, pass

class Car(object):

“Create an instance of a class” create a new object named my_car that is an instance of Car.

class Car(object):
my_car = Car()

“Class member variables” creates a new member variable named condition as "new".

class Car(object):
   condition = "new"
my_car = Car()

“Calling class member variables” prints statement to display the condition of my_car.

class Car(object):
  condition = "new"
my_car = Car()
print my_car.condition

“Initializing a class”

class Car(object):
 condition = "new"
 def __init__(self, model, color, mpg):
   self.model = model
   self.color = color
   self.mpg = mpg
my_car = Car("DeLorean","silver",88)
print my_car.condition

“Referring to member variables”

class Car(object):
 condition = "new"
 def __init__(self, model, color, mpg):
   self.model = model
   self.color = color
   self.mpg = mpg
my_car = Car("DeLorean","silver",88)
print my_car.condition
print my_car.color
print my_car.model
print my_car.mpg

“Creating class methods”

class Car(object):
 condition = "new"
 def __init__(self, model, color, mpg):
   self.model = model
   self.color = color
   self.mpg = mpg
 def display_car(self):
   return "This is a %s %s with %d MPG." % (self.color,self.model, self.mpg)
my_car = Car("DeLorean", "silver", 88)
print my_car.display_car()

“Modifying member variables”

class Car(object):
 condition = "new"
 def __init__(self, model, color, mpg):
   self.model = model
   self.color = color
   self.mpg = mpg
 def display_car(self):
   return "This is a %s %s with %d MPG." % (self.color,self.model, self.mpg)
 def drive_car(self):
   self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.condition

“Inheritance” creates a class ElectricCar that inherits from Car

class Car(object):
 condition = "new"
 def __init__(self, model, color, mpg):
   self.model = model
   self.color = color
   self.mpg = mpg
 def display_car(self):
   return "This is a %s %s with %d MPG." % (self.color,self.model, 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
my_car = ElectricCar("moas", "silver", 88,"molten salt")

“Overriding methods”

class Car(object):
 condition = "new"
 def __init__(self, model, color, mpg):
   self.model = model
   self.color = color
   self.mpg = mpg
 def display_car(self):
    return "This is a %s %s with %d MPG." % (self.color,self.model, 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"
my_car = ElectricCar("moas", "silver", 88,"molten salt")
print my_car.condition
print my_car.condition

“Building useful classes” defines a Point3D class that inherits from object

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

“See It to Believe It” prints in output.txt the squares of numbers from 1 to 10

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")

The open() Function creates a variable, my_file that allow you to read and write to it!

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "w")
for n in my_list:

“Reading”  creates my_file, and set it equal to the file open() with both "output.txt" and r

my_file = open("output.txt","r")

“Reading Between the Lines”, in this particular case, modify the content of text.txt

my_file = open("text.txt","r")
print my_file.readline()
print my_file.readline()
print my_file.readline()

“PSA: Buffering Data”

# 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.")
# Try to read from the file

“The ‘with’ and ‘as’ Keywords” we don’t explicitly close() our file, and remember that if we don’t close a file, our data will get stuck in the buffer.

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

“Try It Yourself” writes any data you like to the text.txt file using withas

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

“Case Closed?” checks if the file is not .closed

with open("text.txt", "w") as textfile:
 textfile.write("Hola mundo!")
 if my_file.closed != True:
print my_file.closed


About Julita Inca

Ingeniero de Sistemas UNAC, Magíster en Ciencias de la Computación PUCP, OPW GNOME 2011, Miembro de la GNOME Foundation desde el 2012, Embajadora Fedora Perú desde el 2012, ganadora del scholarship of the Linux Foundation 2012, experiencia como Admin Linux en GMD y Especialista IT en IBM, con certificaciones RHCE, RHCSA, AIX 6.1, AIX 7 Administrator e ITILv3. Experiencia académica en universidades como PUCP, USIL y UNI. HPC researcher, a simple mortal, like you!
This entry was posted in τεχνολογια :: Technology and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s