You are on page 1of 30

Escaping characters:

'There's a snake in my boot!'

This code breaks because Python thinks the apostrophe in 'There's' ends the
string. We can use the backslash to fix the problem, like this:

'There\'s a snake in my boot!'


pi=3.14
print str(pi)

parrot = "norwegian blue"
print parrot.upper()

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

parrot="Norwegian Blue"
print len(parrot)

fifth_letter = "MONTY"[4]
print fifth_letter

print "Life " + "of " + "Brian"

print "The value of pi is around " + str(3.14)

string_1 = "Camelot"
string_2 = "place"

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

from datetime import datetime

from datetime import datetime
now=datetime.now()
print now
print now.year
print now.month
print now.day

print '%02d/%02d/%04d' % (now.month, now.day, now.year)

from datetime import datetime
now = datetime.now()
print '%02d:%02d:%04d' %(now.hour,now.minute,now.second)

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

original = raw_input("Enter a word:")

print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0 and original.isalpha():
  print original
else:
  print "empty"

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
  word = original.lower()
  first = word[0]
  new_word = word + first + pyg
  new_word = new_word[1:len(new_word)]
else:
    print 'empty'
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)

def square(n):
  """Returns the square of a number."""
  squared = n ** 2
  print "%d squared is %d." % (n, squared)
  return squared
  
# Call the square function on line 10! Make sure to
# include the number 10 between the parentheses.
square(10)

The values of parameter passed on the def power(base,exponent):  # Add your 


function called arguments
parameters here!
 When defining a function,   result = base ** exponent
placeholder variables are called   print "%d to the power of %d is %d.
parameters.
" % (base, exponent, result)
 When using, or calling, a function,
inputs into the function are called
arguments. power(37, 4)  # Add your arguments he
re!

import math def one_good_turn(n):
print math.sqrt(25)   return n + 1
    
def deserves_another(m):
  return one_good_turn(m) + 2

absolute = abs(-42) def cube(number):
  return number * number * number
Min(),max()

def by_three(number):
print type(12)   if number % 3 == 0:
print type(2.33)     return cube(number)
print type("medha")   else:
    return False

It’s possible to import only from math import sqrt


certain variables or functions
from a given module. Pulling in
just a single function from a Universal import
module is called a function # Import *everything* from the math m
import, and it’s done with the odule on line 3!
from keyword:
from math import *

Here Be Dragons

Universal imports may look great on


the surface, but they’re not a good
idea for one very important reason:
they fill your program with a ton of
variable and function names without
the safety of those names still being
associated with the module(s) they
came from.

def biggest_number(*args): def shut_down(s):
  print max(args)   if s == "yes":
  return max(args)     return "Shutting down"
       elif s == "no":
def smallest_number(*args):     return "Shutdown aborted"
  print min(args)   else:
  return min(args)     return "Sorry"

def distance_from_zero(arg):
def distance_from_zero(num):
  print abs(arg)
  if type(num) == int or type(num) == 
  return abs(arg)
float:
biggest_number(-10, -5, 5, 10)     return abs(num)
smallest_number(-10, -5, 5, 10)   else:
distance_from_zero(-10)     return "Nope"

zoo_animals = ["pangolin", "cass suitcase = [] 
owary", "sloth", "tiger"] suitcase.append("sunglasses")
zoo_animals[3]="dogs"
# Your code here!
my_list = [1,9,3,8,5,7] suitcase.append("shirt")
suitcase.append("pants")
for number in my_list: suitcase.append("shoes")
  # Your code here
  print 2*number list_length = len(suitcase)
  

suitcase = ["sunglasses", "hat",  //slicing
"passport", "laptop", "suit", "s animals = "catdogfrog"
hoes"]
# The first three characters of anima
# The first and second items (in ls
dex zero and one) cat = animals[:3]
first = suitcase[0:2]
# The fourth through sixth characters
# Third and fourth items (index  dog = animals[3:6]
two and three)
middle = suitcase[2:4] # From the seventh character to the e
nd
# The last two items (index four  frog = animals[6:]
and five)
last = suitcase[4:6]  

animals = ["aardvark", "badger",  start_list = [5, 3, 1, 2, 4]
"duck", "emu", "fennec fox"] square_list = []
duck_index = animals.index("duck
")# Use index() to find "duck" # Your code here!
for number in start_list:
# Your code here!   square_list.append(number ** 2)
animals.insert(duck_index,"cobra square_list.sort()
")
print square_list
print animals

# Assigning a dictionary with th Like Lists, Dictionaries are mutable


ree key-value pairs to residents menu = {} # Empty dictionary
: menu['Chicken Alfredo'] = 14.50 # Add
residents = {'Puffin' : 104, 'Sl ing new key-value pair
oth' : 105, 'Burmese Python' : 1 print menu['Chicken Alfredo']
06}
# Your code here: Add some dish-price 
print residents['Puffin'] # Prin pairs to menu!
ts Puffin's room number
menu['pizza']=23.09
# Your code here! menu['cold drink']=3.01
print residents['Sloth'] menu['chai']=2.00
print residents['Burmese Python'
]
print "There are " + str(len(menu)) + 
" items on the menu."
print menu

backpack = ['xylophone', 'dagger del zoo_animals['Sloth']
', 'tent', 'bread loaf'] del zoo_animals['Bengal Tiger']
backpack.remove("dagger") zoo_animals['Rockhopper Penguin'] = '
Plains Exhibit'

Taking a vacation:
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):
  cost = days * 40
  if days >= 7:
    cost -= 50
  elif days >= 3:
    cost -= 20
  return cost
def trip_cost(city, days, spending_money):
  return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(cit
y) + spending_money

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

Add a key to inventory called 'pocket'

Set the value of 'pocket' to be a list consisting of the strings 'seashell',


'strange berry', and 'lint'

.sort() the items in the list stored under the 'backpack' key

Then .remove('dagger') from the list of items stored under the 'backpack' key

Add 50 to the number stored under the 'gold' key

inventory = {
  'gold' : 500,
  'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'p
ouch' 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

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

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

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

# Write your function below!
def fizz_count(x):
  count = 0
  for item in x:
    if item == "fizz":
      count = count + 1
  return count

for letter in "Codecademy":
  print letter
    
# Empty lines to make the output pretty
print
print

word = "Programming is fun!"
for letter in word:
  # Only print out the letter i
  if letter == "i":
    print letter
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

for food in prices:
  print food
  print "price: %s" % prices[food]
  print "stock: %s" % stock[food]
total = 0
for food in prices:
  print prices[food] * stock[food]
  total = total + prices[food] * stock[food]
print total

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

lloyd = {
  "name": "Lloyd",
  "homework": [],
  "quizzes": [],
  "tests": []
}
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]
for student in students:
  print student["name"]
  print student["homework"]
  print student["quizzes"]
  print student["tests"]
def average(numbers):
  total = sum(numbers)
  total = float(total)
  return total / len(numbers)
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

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"
  
print get_letter_grade(get_average(lloyd))
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

def get_class_average(class_list):
  results = []
  for student in class_list:
    student_avg = get_average(student)
    results.append(student_avg)
  return average(results)

  students=[alice, lloyd, tyler]

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)

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

print my_function(range(3))

n = [3, 5, 7]

def total(numbers):
  result = 0
  for i in range(0,len(numbers)):
    result += numbers[i]
  return result

n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
  result = ""
  for word in words:
    result += word
  return result

print join_strings(n)

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here

def flatten(lists):
  results = []
  for numbers in lists:
    for number in numbers:
      results.append(number)
  return results

print flatten(n)

Create a 5 x 5 grid board = []


initialized to all ‘O’s and for i in range(5):
store it in board.   board.append(['O'] * 5)
Print board
 Use range() to loop
5 times.
 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.

Custom print: board = []


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

def print_board(board_in):
  for row in board:
    print row
    
print_board(board)

Printing pretty

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

from random import from random import randint 


randintcoin =
randint(0, 1)dice =
randint(1, 6)
def random_row(board_in):
  return randint(0, len(board_in) - 1)
    
def random_col(board_in):
  return randint(0, len(board_in) - 1)

random_row(board)
random_col(board)

...and Seek! ship_row = random_row(board)


ship_col = random_col(board)
number =
raw_input("Enter a
number: ")if # Add your code below!
int(number) == 0: guess_row = int(raw_input("Guess Row: "))
print "You entered guess_col = int(raw_input("Guess Col: "))
0"

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)

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 be in your for 
loop
# don't forget to properly indent!
for turn in range(4):
  print "Turn", turn + 1
  guess_row = int(raw_input("Guess Row: "))
  guess_col = int(raw_input("Guess Col: "))

  if guess_row == ship_row and guess_col == shi
p_col:
    print "Congratulations! You sank my battles
hip!"
    break
  else:
    if guess_row not in range(5) or \
      guess_col not in range(5):
      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!"
      board[guess_row][guess_col] = "X"
    if (turn == 3):
      print "Game Over"
    print_board(board)
num = 1

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

choice = raw_input('Enjoying the course? (y/n)'
)

while choice != 'y' and choice != 'n':  # Fill 
in the condition (before the colon)
  choice = raw_input("Sorry, I didn't catch tha
t. Enter again: ")

Count =0
While True
Print count
Count+=1
If count>=10
break
import random

print "Lucky Numbers! 3 numbers will be generat
ed."
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!"
    break
  count += 1
else:
  print "You win!"

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left>0:
  guess=int(raw_input("Your guess: "))
  if guess==random_number:
    print "You win!"
    break
    guesses_left-=1
  else:
    print "You lose"
To print 0=19 :
for i in range(20):
  print i

hobbies = []

# Add your code below!

for num in range(3):
  hobby =  raw_input("Tell me one of your favorite hobbies: ")
  hobbies.append(hobby)

print hobbies

thing = "spam!"

for c in thing:
  print c

phrase = "A bird in the hand..."

# Add your for loop
for char in phrase:
  if char=="A" or char=="a":
    print "X",
  else:
    print char,

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
  # Your code here!
  print key, d[key]
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
Your choices are:1 pizza2 pasta3 salad4 nachos

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

If number is integer:
def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  return absolute - rounded == 0

print is_int(10)
print is_int(10.5)

def digit_sum(n):
  total = 0
  string_n = str(n)
  for char in string_n:
    total += int(char)
  return total

#Alternate Solution:

#def digit_sum(n):
#  total = 0
#  while n > 0:
#    total += n % 10
#    n = n // 10
#  return total
  
print digit_sum(1234)

Factorial:
def factorial(x):
    total = 1
    while x>0:
        total *= x
        x-=1
    return total
  
print factorial(5)

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

print is_prime(13)
print is_prime(10)

Reverse string: def reverse(text):


def reverse(text):     word = ""
  text2=text[::-1]     l = len(text) - 1
  return text2     while l >= 0:
        word = word + text[l]
        l -= 1
    return word
  
print reverse("Hello World")

antivowel def anti_vowel(text):
    result = ""
    vowels = "ieaouIEAOU"
    for char in text:
          if char not in vowels:
            result += char
    return result
print anti_vowel("hello book")

scrabble_score 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):
  word = word.lower()
  total = 0
  for letter in word:
    for leter in score:
      if letter == leter:
        total = total + score[leter]
  return total

print scrabble_score("pizza")

censor def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    count = 0
    for i in words:
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

    return result
  
print censor("this hack is wack hack", "hack")

count def count(sequence, item):
    count = 0
    for i in sequence:
        if i == item:
            count += 1
    return count
  
print count([1, 2, 1, 1], 1)

def purify(lst):
    res = []
    for ele in lst:
        if ele % 2 == 0:
            res.append(ele)
    return res
  
print purify([1, 2, 3, 4])

Lst multiplicaton def product(list):


  total = 1
  for num in list:
    total = total * num
  return total

print product([4, 5, 5])

def remove_duplicates(inputlist):
    if inputlist == []:
        return []
    
    # Sort the input list from low to high    
    inputlist = sorted(inputlist)
    # Initialize the output list, and give it t
he first value of the now-sorted input list
    outputlist = [inputlist[0]]

    # Go through the values of the sorted list 
and append to the output list
    # ...any values that are greater than the l
ast value of the output list
    for i in inputlist:
        if i > outputlist[-1]:
            outputlist.append(i)
        
    return outputlist
  
print remove_duplicates([1, 1, 2, 2])

median def median(lst):
    sorted_list = sorted(lst)
    if len(sorted_list) % 2 != 0:
        #odd number of elements
        index = len(sorted_list)//2 
        return sorted_list[index]
    elif len(sorted_list) % 2 == 0:
        #even no. of elements
        index_1 = len(sorted_list)/2 - 1
        index_2 = len(sorted_list)/2
        mean = (sorted_list[index_1] + sorted_l
ist[index_2])/2.0
        return mean
   
print median([2, 4, 5, 9])

Define a function, grades_std_deviation, that takes one argument called


variance.

return the result of variance ** 0.5

After the function, create a new variable called variance and store the result of
calling grades_variance(grades).

Finally print the result of calling grades_std_deviation(variance).

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

def print_grades(grades_input):
  for grade in grades_input:
    print grade

def grades_sum(scores):
  total = 0
  for score in scores: 
    total += score
  return total
    
def grades_average(grades_input):
  sum_of_grades = grades_sum(grades_input)
  average = sum_of_grades / float(len(grades_input))
  return average

def grades_variance(grades):
    variance = 0
    for number in grades:
        variance += (grades_average(grades) - number) ** 2
    return variance / len(grades)

def grades_std_deviation(variance):
  return variance ** 0.5

variance = grades_variance(grades)

for grade in grades:
  print grade
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(variance)

How to print all my_dict = {


keys and resp.
Values in dict.   "Name": "Guido",
  "Age": 22,
  "BDFL": False
}
print my_dict.items()

Only keys or print my_dict.keys()


values
print my_dict.values()

For iterating over my_dict = {


lists,tuples,dict
and string: in   "Name": "Guido",
for number   "Age": 22,
in range(5):   "BDFL": False
print }
number,
for key in my_dict:
d = {
"name":   print key, my_dict[key]
"Eric",
"age": 26 evens_to_50 = [i for i in range(51) if i % 2 == 0]
} print evens_to_50
for key in
d: div_3=[i for i in range(100) if i%3==0]
print key,
d[key], print div_3
for letter
in "Eric":
print
letter, #
note the
comma!

List doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 
Comprehensio == 0]
n Syntax
# Complete the following line. Use the line above for hel
p.
even_squares = [x**2 for x in range(1,11) if (x**2)%4==0]
print even_squares

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


Print cubes_by_four
List slicing l = [i ** 2 for i in range(1, 11)]
syntax:
[start:end:stride] # Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

Omitting indices: my_list = range(1, 11) # List of numbers 1 - 10

# Add your code below!
print my_list[::2]
print my_list[2:]
to_five = ['A', 'B', 'C', 'D', 'E']
print to_five[3:]# prints ['D', 'E']
print to_five[:2]# prints ['A', 'B']
print to_five[::2]# print ['A', 'C', 'E']

Reversing string my_list = range(1, 11)

# Add your code below!
backwards=my_list[::-1]
print backwards

Stride length to_one_hundred = range(101)


# Add your code below!
backwards_by_tens=to_one_hundred[::-10]
print backwards_by_tens
Create a list, to_21 = range(1, 22)
to_21, that’s
just the odds = to_21[::2]
numbers from
1 to 21, middle_third = to_21[7:14]
inclusive.

Create a
second list,
odds, that
contains only
the odd
numbers in
the to_21 list
(1, 3, 5, and so
on). Use list
slicing for this
one instead of
a list
comprehensio
n.

Finally, create
a third list,
middle_third
, that’s equal
to the middle
third of to_21,
from 8 to 14,
inclusive.

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
[0, 3, 6, 9, 12, 15]
anguages = ["HTML", "JavaScript", "Python", "Ruby"]

# Add arguments to the filter()
print filter(lambda x: x == "Python", languages)

squares = [x ** 2 for x in range(1, 11)]

print filter(lambda x: x >= 30 and x <= 70, squares)

threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0
]
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"

message = garbled[::-2]
str = "ABCDEFGHIJ"
start, end, stride = 1, 6, 2
str[start:end:stride]

arbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXX
sXaXXXXXXgXeX!XX"

message = filter(lambda x: x != "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
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

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

0b10 b100 b110 b1000 b101


rint 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)
1 2 7 4 5 201

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)
print bin(0b1110 & 0b101)
print bin(0b1110 | 0b101)
print bin(0b1110 ^ 0b101)
Xor
Not operator:print ~1
print ~2
print ~3
print ~42
print ~123

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

a = 0b10111011

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

a = 0b11101110

mask = 0b11111111
desired = a ^ mask

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

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

Classier classes class Animal(object):


  def __init__(self):
    pass

lass Animal(object):
  def __init__(self, name):
    self.name = name
    
zebra = Animal("Jeffrey")

print zebra.name
methods class Animal(object):
  """Makes cute animals."""
  is_alive = True
  def __init__(self, name, age):
    self.name = name
    self.age = age
  # Add your method here!
  def description(self):
    print self.name
    print self.age
    
hippo = Animal("Anderson", 36)
hippo.description()

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

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

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

f.close()

Open file my_file=open("output.txt","r+")

write my_list = [i ** 2 for i in range(1, 11)]

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

# Add your code below!
for value in my_list:
  my_file.write(str(value) + "\n")
  
my_file.close()
read my_file = open("output.txt", "r")
print my_file.read()
my_file.close()

Read between lines my_file = open("text.txt", "r")


print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()

# Use a file handler to open a file for writing
write_file = open("text.txt", "w")

# Open the file for reading
read_file = open("text.txt", "r")

# 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()

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")
  
if not file.closed:
  file.close()

print my_file.closed

We keep telling you that you always need to close your files after you’re done
writing to them. Here’s why!
During the I/O process, data is buffered: this means that it is held in a temporary
location before being written to the file.

Python doesn’t flush the buffer—that is, write data to the file—until it’s sure you’re
done writing. One way to do this is to close the file. If you write to a file without
closing, the data won’t make it to the target file.

You might also like