├── ex17 ├── new_file.txt ├── test.txt └── ex17.py ├── ex46 └── projects │ └── skeleton │ ├── NAME │ └── __init__.py │ ├── tests │ ├── __init__.py │ └── NAME_tests.py │ └── setup.py ├── ex16 ├── test.txt └── ex16.py ├── ex20 ├── test.txt ├── ex20.py └── sd20.py ├── ex25.pyc ├── README.md ├── ex15 ├── ex15_sample.txt ├── ex15.py └── sd15.py ├── ex44 ├── ex44a.py ├── ex44b.py ├── ex44c.py ├── ex44d.py └── ex44e.py ├── ex1.py ├── ex33.py ├── ex10.py ├── ex2.py ├── ex9.py ├── ex6.py ├── ex40.py ├── ex30.py ├── ex7.py ├── ex13.py ├── ex29.py ├── ex18.py ├── sd5_1.py ├── ex12.py ├── ex5.py ├── ex38.py ├── ex11.py ├── ex21.py ├── ex8.py ├── ex32.py ├── sd5_2.py ├── ex25.py ├── ex24.py ├── ex31.py ├── sd30.py ├── sd33.py ├── ex3.py ├── ex4.py ├── sd6_1.py ├── ex14.py ├── sd7.py ├── ex19.py ├── ex42.py ├── ex39.py ├── ex35.py ├── oop_test.py ├── sd39.py ├── ex26.py └── ex43.py /ex17/new_file.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ex17/test.txt: -------------------------------------------------------------------------------- 1 | This is a test file. 2 | -------------------------------------------------------------------------------- /ex46/projects/skeleton/NAME/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ex46/projects/skeleton/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ex16/test.txt: -------------------------------------------------------------------------------- 1 | This is a test file for exercise sixteen. 2 | -------------------------------------------------------------------------------- /ex20/test.txt: -------------------------------------------------------------------------------- 1 | This is line 1 2 | This is line 2 3 | This is line 3 4 | -------------------------------------------------------------------------------- /ex25.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsquared21/Learn-Python-The-Hard-Way/HEAD/ex25.pyc -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn-Python-The-Hard-Way 2 | My solutions to Learn Python the Hard Way by Zed A. Shaw (3rd Edition) 3 | -------------------------------------------------------------------------------- /ex15/ex15_sample.txt: -------------------------------------------------------------------------------- 1 | This is stuff I typed into a file. 2 | It is really cool stuff. 3 | Lots and lots of fun to have in here. -------------------------------------------------------------------------------- /ex46/projects/skeleton/tests/NAME_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import NAME 3 | 4 | def setup(): 5 | print "SETUP!" 6 | 7 | def teardown(): 8 | print "TEAR DOWN!" 9 | 10 | def test_basic(): 11 | print "I RAN!" -------------------------------------------------------------------------------- /ex44/ex44a.py: -------------------------------------------------------------------------------- 1 | class Parent(object): 2 | 3 | def implicit(self): 4 | print "PARENT implicit()" 5 | 6 | class Child(Parent): 7 | pass 8 | 9 | dad = Parent() 10 | son = Child() 11 | 12 | dad.implicit() 13 | son.implicit() -------------------------------------------------------------------------------- /ex1.py: -------------------------------------------------------------------------------- 1 | print "Hello World" 2 | print "Hello Again" 3 | print "I like typing this." 4 | print "this is fun." 5 | print 'Yay! Printing.' 6 | print "I'd much rather you 'not'." 7 | print 'I "said" do not touch this.' 8 | print "Printing another line." -------------------------------------------------------------------------------- /ex44/ex44b.py: -------------------------------------------------------------------------------- 1 | class Parent(object): 2 | 3 | def override(self): 4 | print "PARENT override()" 5 | 6 | class Child(Parent): 7 | 8 | def override(self): 9 | print "CHILD override()" 10 | 11 | dad = Parent() 12 | son = Child() 13 | 14 | dad.override() 15 | son.override() -------------------------------------------------------------------------------- /ex33.py: -------------------------------------------------------------------------------- 1 | i = 0 2 | numbers = [] 3 | 4 | while i < 6: 5 | print "At the top i is %d" % i 6 | numbers.append(i) 7 | 8 | i = i + 1 9 | print "Numbers now: ", numbers 10 | print "At the bottom i is %d" % i 11 | 12 | 13 | print "The numbers: " 14 | 15 | for num in numbers: 16 | print num -------------------------------------------------------------------------------- /ex15/ex15.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script, filename = argv 4 | 5 | txt = open(filename) 6 | 7 | print "Here's your file %r:" % filename 8 | print txt.read() 9 | 10 | print "Type the filename again:" 11 | file_again = raw_input("> ") 12 | 13 | txt_again = open(file_again) 14 | 15 | print txt_again.read() -------------------------------------------------------------------------------- /ex10.py: -------------------------------------------------------------------------------- 1 | tabby_cat = "\tI'm tabbed in." 2 | persian_cat = "I'm split\non a line." 3 | backlash_cat = "I'm \\ a \\ cat." 4 | 5 | fat_cat = """ 6 | I'll do a list: 7 | \t* Cat food 8 | \t* Fishies 9 | \t* Catnip\n\t* Grass 10 | """ 11 | 12 | print tabby_cat 13 | print persian_cat 14 | print backlash_cat 15 | print fat_cat -------------------------------------------------------------------------------- /ex2.py: -------------------------------------------------------------------------------- 1 | # A comment, this is so you can read your program later. 2 | # Anything after the # is ignored by python. 3 | 4 | print "I could have code like this." # and the comment after is ignored 5 | 6 | # You can also use a comment to "disable" or comment out a piece of code 7 | # print "This won't run." 8 | 9 | print "This will run." -------------------------------------------------------------------------------- /ex44/ex44c.py: -------------------------------------------------------------------------------- 1 | class Parent(object): 2 | 3 | def altered(self): 4 | print "PARENT altered()" 5 | 6 | class Child(Parent): 7 | 8 | def altered(self): 9 | print "CHILD BEFOR PARENT altered()" 10 | super(Child, self).altered() 11 | print "CHILD AFTER PARENT altered()" 12 | 13 | dad = Parent() 14 | son = Child() 15 | 16 | dad.altered() 17 | son.altered() -------------------------------------------------------------------------------- /ex9.py: -------------------------------------------------------------------------------- 1 | # Here's some strange stuff, remeber type it exactly. 2 | 3 | days = "Mon Tue Wed Thu Fri Sat Sun" 4 | months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" 5 | 6 | print "Here are the days: ", days 7 | print "Here are the months: ", months 8 | 9 | print """ 10 | There's something going on here. 11 | With the three double-quotes. 12 | We'll be able to type as much as we like. 13 | Even 4 lines if we want, or 5, or 6. 14 | """ -------------------------------------------------------------------------------- /ex6.py: -------------------------------------------------------------------------------- 1 | x = "There are %d types of people." % 10 2 | binary = "binary" 3 | do_not = "don't" 4 | y = "Those who know %s and those who %s." % (binary, do_not) 5 | 6 | print x 7 | print y 8 | 9 | print "I said: %r." % x 10 | print "I also said: '%s'." % y 11 | 12 | hilarious = False 13 | joke_evaluation = "Isn't that joke so funny?! %r" 14 | 15 | print joke_evaluation % hilarious 16 | 17 | w = "This is the left side of..." 18 | e = "a string with a right side." 19 | 20 | print w + e -------------------------------------------------------------------------------- /ex40.py: -------------------------------------------------------------------------------- 1 | class Song(object): 2 | 3 | def __init__(self, lyrics): 4 | self.lyrics = lyrics 5 | 6 | def sing_me_a_song(self): 7 | for line in self.lyrics: 8 | print line 9 | 10 | happy_bday = Song(["Happy birthday to you", 11 | "I don't want to get sued", 12 | "So I'll stop right there"]) 13 | 14 | bulls_on_parade = Song(["They rally around tha family", 15 | "with pockets full of shells"]) 16 | 17 | happy_bday.sing_me_a_song() 18 | 19 | bulls_on_parade.sing_me_a_song() -------------------------------------------------------------------------------- /ex46/projects/skeleton/setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | config = { 7 | 'description': 'My project', 8 | 'author': 'Jabari James', 9 | 'url': 'URL to get it at.', 10 | 'download_url': 'Where to download it.', 11 | 'author_email': 'jabarimail@gmail.com', 12 | 'version': '0.1', 13 | 'install_requires': ['nose'], 14 | 'packages': ['NAME'], 15 | 'scripts': [], 16 | 'name': 'projectname' 17 | } 18 | 19 | setup(**config) -------------------------------------------------------------------------------- /ex30.py: -------------------------------------------------------------------------------- 1 | people = 30 2 | cars = 40 3 | trucks = 15 4 | 5 | 6 | if cars > people: 7 | print "We should take the cars." 8 | elif cars < people: 9 | print "We should not take the cars." 10 | else: 11 | print "We can't decide." 12 | 13 | if trucks > cars: 14 | print "That's too many trucks." 15 | elif trucks < cars: 16 | print "Maybe we could take the trucks." 17 | else: 18 | print "We still can't decide." 19 | 20 | if people > trucks: 21 | print "Alright, let's just take the trucks." 22 | else: 23 | print "Fine, let's stay home then." -------------------------------------------------------------------------------- /ex7.py: -------------------------------------------------------------------------------- 1 | print "Mary has a little lamb." 2 | print "Its fleece was white as %s." % 'snow' 3 | print "And everywhere that Mary went." 4 | print "." * 10 # what'd that do? 5 | 6 | end1 = "C" 7 | end2 = "h" 8 | end3 = "e" 9 | end4 = "e" 10 | end5 = "s" 11 | end6 = "e" 12 | end7 = "B" 13 | end8 = "u" 14 | end9 = "r" 15 | end10 = "g" 16 | end11 = "e" 17 | end12 = "r" 18 | 19 | # watch that comma at the end. try removing it to see what happens 20 | print end1 + end2 + end3 + end4 + end5 + end6, 21 | print end7 + end8 + end9 + end10 + end11 + end12 -------------------------------------------------------------------------------- /ex13.py: -------------------------------------------------------------------------------- 1 | # Impor the argv method from the sys module 2 | from sys import argv 3 | 4 | # Assign the arguement variables to the variables 5 | # script, first, second, third 6 | script, first, second, third = argv 7 | 8 | # Display a string and the variable script 9 | print "The script is called:", script 10 | # Display a string and the variable first 11 | print "Your first variable is:", first 12 | # Display a string and the variable second 13 | print "Your second variable is:", second 14 | # Display a string and the variable third 15 | print "Your third variable is:", third -------------------------------------------------------------------------------- /ex29.py: -------------------------------------------------------------------------------- 1 | people = 20 2 | cats = 30 3 | dogs = 15 4 | 5 | 6 | if people < cats: 7 | print "Too many cats! The world is doomed!" 8 | 9 | if people > cats: 10 | print "Not many cats! The world is saved!" 11 | 12 | if people < dogs: 13 | print "The world i drooled on!" 14 | 15 | if people > dogs: 16 | print "The world is dry!" 17 | 18 | 19 | dogs += 5 20 | 21 | if people >= dogs: 22 | print "People are greater than or equal to dogs." 23 | 24 | if people <= dogs: 25 | print "People are less than or equal to dogs." 26 | 27 | if people == dogs: 28 | print "People are equal to dogs." -------------------------------------------------------------------------------- /ex18.py: -------------------------------------------------------------------------------- 1 | # this one is like your scripts with argv 2 | def print_two(*args): 3 | arg1, arg2 = args 4 | print "arg1: %r, arg2: %r" % (arg1, arg2) 5 | 6 | # ok, that *args is acturally pointless, we can just do this 7 | def print_two_again(arg1, arg2): 8 | print "arg1: %r, arg2: %r" % (arg1, arg2) 9 | 10 | # this just takes one argument 11 | def print_one(arg1): 12 | print "arg1: %r" % arg1 13 | 14 | # this one takes no argument 15 | def print_none(): 16 | print "I got nothin'." 17 | 18 | 19 | print_two("Zed", "Shaw") 20 | print_two_again("Zed", "Shaw") 21 | print_one("Frist!") 22 | print_none() -------------------------------------------------------------------------------- /sd5_1.py: -------------------------------------------------------------------------------- 1 | name = 'Zed A. Shaw' 2 | age = 35 # not a lie 3 | height = 74 # inches 4 | weight = 180 # lbs 5 | eyes = 'Blue' 6 | teeth = 'White' 7 | hair = 'Brown' 8 | 9 | print "Let's talk about %s." % name 10 | print "He's %d inches tall." % height 11 | print "He's %d pounds heavy." % weight 12 | print "Actually that's not too heavy." 13 | print "He's got %s eyes and %s hair." % (eyes, hair) 14 | print "His teeth are usually %s depending on the coffee." % teeth 15 | 16 | # this line is tricky, try to get it exactly right 17 | print "If I add %d, %d and %d I get %d." % ( 18 | age, height, weight, age + height + weight) -------------------------------------------------------------------------------- /ex12.py: -------------------------------------------------------------------------------- 1 | # Prompt the user with the string "How old are you? " 2 | # assign the input to the variable age 3 | age = raw_input("How old are you? ") 4 | # Prompt the user with the string "How tall are you? " 5 | # assign the input to the variable height 6 | height = raw_input("How tall are you? ") 7 | # Prompt the user with the string "How much do you weigh? " 8 | # assign the input to the variable weight 9 | weight = raw_input("How much do you weigh? ") 10 | 11 | # Insert the age, height and weight variable into 12 | # the string format and display the string 13 | print "So, you're %r old, %r tall and %r heavy." % ( 14 | age, height, weight) -------------------------------------------------------------------------------- /ex17/ex17.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | from os.path import exists 3 | 4 | script, from_file, to_file = argv 5 | 6 | print "Copying from %s to %s" % (from_file, to_file) 7 | 8 | # we could do these two on one line, how? 9 | in_file = open(from_file) 10 | indata = in_file.read() 11 | 12 | print "The input file is %d bytes long" % len(indata) 13 | 14 | print "Does the output file exist? %r" % exists(to_file) 15 | print "Ready, hit RETURN to continue, CTRL-C to abort." 16 | raw_input() 17 | 18 | out_file = open(to_file, 'w') 19 | out_file.write(indata) 20 | 21 | print "Alright, all done." 22 | 23 | out_file.close() 24 | in_file.close() -------------------------------------------------------------------------------- /ex44/ex44d.py: -------------------------------------------------------------------------------- 1 | class Parent(object): 2 | 3 | def override(self): 4 | print "PARENT override()" 5 | 6 | def implicit(self): 7 | print "PARENT implicit()" 8 | 9 | def altered(self): 10 | print "PARENT altered()" 11 | 12 | class Child(Parent): 13 | 14 | def override(self): 15 | print "CHILD override()" 16 | 17 | def altered(self): 18 | print "CHILD, BEFORE PARENT altered()" 19 | super(Child, self).altered() 20 | print "CHILD, AFTER PARENT altered()" 21 | 22 | dad = Parent() 23 | son = Child() 24 | 25 | dad.implicit() 26 | son.implicit() 27 | 28 | dad.override() 29 | son.override() 30 | 31 | dad.altered() 32 | son.altered() -------------------------------------------------------------------------------- /ex44/ex44e.py: -------------------------------------------------------------------------------- 1 | class Other(object): 2 | 3 | def override(self): 4 | print "OTHER override()" 5 | 6 | def implicit(self): 7 | print "OTHER implicit()" 8 | 9 | def altered(self): 10 | print "OTHER altered()" 11 | 12 | class Child(object): 13 | 14 | def __init__(self): 15 | self.other = Other() 16 | 17 | def implicit(self): 18 | self.other.implicit() 19 | 20 | def override(self): 21 | print "CHILD override()" 22 | 23 | def altered(self): 24 | print "CHILD, BEFORE OTHER altered()" 25 | self.other.altered() 26 | print "CHILD, AFTER OTHER altered()" 27 | 28 | son = Child() 29 | 30 | son.implicit() 31 | son.override() 32 | son.altered() -------------------------------------------------------------------------------- /ex5.py: -------------------------------------------------------------------------------- 1 | my_name = 'Zed A. Shaw' 2 | my_age = 35 # not a lie 3 | my_height = 74 # inches 4 | my_weight = 180 # lbs 5 | my_eyes = 'Blue' 6 | my_teeth = 'White' 7 | my_hair = 'Brown' 8 | 9 | print "Let's talk about %s." % my_name 10 | print "He's %d inches tall." % my_height 11 | print "He's %d pounds heavy." % my_weight 12 | print "Actually that's not too heavy." 13 | print "He's got %s eyes and %s hair." % (my_eyes, my_hair) 14 | print "His teeth are usually %s depending on the coffee." % my_teeth 15 | 16 | # this line is tricky, try to get it exactly right 17 | print "If I add %d, %d and %d I get %d." % ( 18 | my_age, my_height, my_weight, my_age + my_height + my_weight) -------------------------------------------------------------------------------- /ex38.py: -------------------------------------------------------------------------------- 1 | ten_things = "Apples Oranges Crows Telephone Light Sugar" 2 | 3 | print "Wait there are not 10 things in that list. Let's fix that." 4 | 5 | stuff = ten_things.split(' ') 6 | more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 7 | 8 | while len(stuff) != 10: 9 | next_one = more_stuff.pop() 10 | print "Adding: ", next_one 11 | stuff.append(next_one) 12 | print "There are %d items now." % len(stuff) 13 | 14 | print "There we go: ", stuff 15 | 16 | print "Let's do some things with stuff." 17 | 18 | print stuff[1] 19 | print stuff[-1] # whoa! fancy 20 | print stuff.pop() 21 | print ' '.join(stuff) # what? cool! 22 | print '#'.join(stuff[3:5]) # super stellar! -------------------------------------------------------------------------------- /ex20/ex20.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script, input_file = argv 4 | 5 | def print_all(f): 6 | print f.read() 7 | 8 | def rewind(f): 9 | f.seek(0) 10 | 11 | def print_a_line(line_count, f): 12 | print line_count, f.readline() 13 | 14 | current_file = open(input_file) 15 | 16 | print "First let's print the while file:\n" 17 | 18 | print_all(current_file) 19 | 20 | print "Now let's rewind, kind of like a tape." 21 | 22 | rewind(current_file) 23 | 24 | print "Let's print three lines:" 25 | 26 | current_line = 1 27 | print_a_line(current_line, current_file) 28 | 29 | current_line = current_line + 1 30 | print_a_line(current_line, current_file) 31 | 32 | current_line = current_line +1 33 | print_a_line(current_line, current_file) -------------------------------------------------------------------------------- /ex11.py: -------------------------------------------------------------------------------- 1 | # Display the string "How old are you?" remove the new line symbol 2 | print "How old are you?", 3 | # Prompt the using to input data and assign it to the variable age 4 | age = raw_input() 5 | # Display the string "How tall are you?" and remove the new line symbol 6 | print "How tall are you?", 7 | # Prompt the user to input data and assign it to the variable height 8 | height = raw_input() 9 | # Display the string "How much do you weigh?" and remove the new line symbol 10 | print "How much do you weigh?", 11 | # Prompt the user to enter data and assign it to the variable weight 12 | weight = raw_input() 13 | 14 | # Insert the variables age, height and weight 15 | # into the formatted string and display it 16 | print "So, your're %r old, %r tall and %r heavy." % ( 17 | age, height, weight) -------------------------------------------------------------------------------- /ex16/ex16.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script, filename = argv 4 | 5 | print "We're going to erase %r." % filename 6 | print "If you don't want that, hit CTRL-C (^C)." 7 | print "If you do want that, hit RETURN." 8 | 9 | raw_input("?") 10 | 11 | print "Opening the file..." 12 | target = open(filename, 'w') 13 | 14 | print "Truncating the file. Goodbye!" 15 | target.truncate() 16 | 17 | print "Now I'm going to ask you for three lines." 18 | 19 | line1 = raw_input("line 1: ") 20 | line2 = raw_input("line 2: ") 21 | line3 = raw_input("line 3: ") 22 | 23 | print "I'm going to write these to the file." 24 | 25 | target.write(line1) 26 | target.write("\n") 27 | target.write(line2) 28 | target.write("\n") 29 | target.write(line3) 30 | target.write("\n") 31 | 32 | print "And finally, we close it." 33 | target.close() -------------------------------------------------------------------------------- /ex21.py: -------------------------------------------------------------------------------- 1 | def add(a, b): 2 | print "ADDING %d + %d" % (a, b) 3 | return a + b 4 | 5 | def subtract(a, b): 6 | print "SUBTRACTING %d - %d" % (a, b) 7 | return a - b 8 | 9 | def multiply(a, b): 10 | print "MULTIPLYING %d * %d" % (a, b) 11 | return a * b 12 | 13 | def divide(a, b): 14 | print "DIVIDING %d / %d" % (a, b) 15 | return a / b 16 | 17 | 18 | print "Let's do some math with just functions!" 19 | 20 | age = add(30, 5) 21 | height = subtract(78, 4) 22 | weight = multiply(90, 2) 23 | iq = divide(100, 2) 24 | 25 | print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) 26 | 27 | 28 | # A puzzle for the extra credit, type it in anyway 29 | print "Here is a puzzle." 30 | 31 | what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) 32 | 33 | print "That becomes: ", what, "Can you do it by hand?" -------------------------------------------------------------------------------- /ex8.py: -------------------------------------------------------------------------------- 1 | # Create a string format and assign it to the variable formatter 2 | formatter = "%r %r %r %r" 3 | 4 | # Insert the integers 1, 2, 3 and 4 into 5 | # the string format and display the string 6 | print formatter % (1, 2, 3, 4) 7 | # Insert the strings "one", "two", "three" and "four" 8 | # into the string format and display the string 9 | print formatter % ("one", "two", "three", "four") 10 | # Insert the booleans True, False, False, True 11 | # into the string format and display the string 12 | print formatter % (True, False, False, True) 13 | # Insert the format into the sring and display it 14 | print formatter % (formatter, formatter, formatter, formatter) 15 | # Insert the strings into the format and display them 16 | print formatter % ( 17 | "I had this thing.", 18 | "That you could type up right.", 19 | "But it didn't sing.", 20 | "So I said goodnight." 21 | ) -------------------------------------------------------------------------------- /ex32.py: -------------------------------------------------------------------------------- 1 | the_count = [1, 2, 3, 4, 5] 2 | fruits = ['apples', 'oranges', 'pears', 'apricots'] 3 | change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] 4 | 5 | # this first kind of for-loop goes throgh a list 6 | for number in the_count: 7 | print "This is count %d" % number 8 | 9 | # same as above 10 | for fruit in fruits: 11 | print "A fruit of type: %s" % fruit 12 | 13 | # also we can go through mixed lists too 14 | # notice we have to use %r since we don't know what's in it 15 | for i in change: 16 | print "I got %r" % i 17 | 18 | # we can also build lists, first start with an empty orange 19 | elements = [] 20 | 21 | # then use the range function to do 0 to 5 counts 22 | for i in range(0, 6): 23 | print "Adding %d to the list." % i 24 | # append is a function that lists understand 25 | elements.append(i) 26 | 27 | # now we can print them out too 28 | for i in elements: 29 | print "Element was: %d" % i -------------------------------------------------------------------------------- /sd5_2.py: -------------------------------------------------------------------------------- 1 | name = 'Zed A. Shaw' 2 | age = 35 # not a lie 3 | height_in_inches = 74 # inches 4 | inches_to_cm = 2.54 # centimeters in an inch 5 | height_in_cm = height_in_inches * inches_to_cm # height in centimeters 6 | weight_in_lbs = 180 # lbs 7 | lbs_to_kgs = 0.453592 # kilograms in a pound 8 | weight_in_kgs = weight_in_lbs * lbs_to_kgs # weight in kilograms 9 | eyes = 'Blue' 10 | teeth = 'White' 11 | hair = 'Brown' 12 | 13 | print "Let's talk about %s." % name 14 | print "He's %d centimeters tall." % height_in_cm 15 | print "He's %d kilograms heavy." % weight_in_kgs 16 | print "Actually that's not too heavy." 17 | print "He's got %s eyes and %s hair." % (eyes, hair) 18 | print "His teeth are usually %s depending on the coffee." % teeth 19 | 20 | # this line is tricky, try to get it exactly right 21 | print "If I add %d, %d and %d I get %d." % ( 22 | age, height_in_inches, weight_in_lbs, age 23 | + height_in_inches + weight_in_lbs) -------------------------------------------------------------------------------- /ex25.py: -------------------------------------------------------------------------------- 1 | def break_words(stuff): 2 | """This function will break up words for us.""" 3 | words = stuff.split(' ') 4 | return words 5 | 6 | def sort_words(words): 7 | """Sorts the words.""" 8 | return sorted(words) 9 | 10 | def print_first_word(words): 11 | """Prints the first word after popping it off.""" 12 | word = words.pop(0) 13 | print word 14 | 15 | def print_last_word(words): 16 | """Prints the last word after popping it off.""" 17 | word = words.pop(-1) 18 | print word 19 | 20 | def sort_sentence(sentence): 21 | """Takes in a full sentence and returns the sorted words.""" 22 | words = break_words(sentence) 23 | return sort_words(words) 24 | 25 | def print_first_and_last(sentence): 26 | """Prints the first and last words of the sentence.""" 27 | words = break_words(sentence) 28 | print_first_word(words) 29 | print_last_word(words) 30 | 31 | def print_first_and_last_sorted(sentence): 32 | """Sorts the words then prints the first and last one.""" 33 | words = sort_sentence(sentence) 34 | print_first_word(words) 35 | print_last_word(words) -------------------------------------------------------------------------------- /ex24.py: -------------------------------------------------------------------------------- 1 | print "Let's practice everything." 2 | print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' 3 | 4 | poem = """ 5 | \tThe lovely world 6 | with logic so firmly planted 7 | cannot discern \n the needs of love 8 | nor comprehend passion from intuition 9 | and requires on explanation 10 | \n\t\twhere there is none. 11 | """ 12 | 13 | print "--------------" 14 | print poem 15 | print "--------------" 16 | 17 | 18 | five = 10 - 2 + 3 - 6 19 | print "This should be five: %s" % five 20 | 21 | def secret_formula(started): 22 | jelly_beans = started * 500 23 | jars = jelly_beans /1000 24 | crates = jars / 100 25 | return jelly_beans, jars, crates 26 | 27 | 28 | start_point = 10000 29 | beans, jars, crates = secret_formula(start_point) 30 | 31 | print "With a starting point of: %d" % start_point 32 | print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 33 | 34 | start_point = start_point / 10 35 | 36 | print "We can also do that this way:" 37 | print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) -------------------------------------------------------------------------------- /ex31.py: -------------------------------------------------------------------------------- 1 | print "You enter a dark room with two doors. Do you go through door #1 or door #2?" 2 | 3 | door = raw_input("> ") 4 | 5 | if door == "1": 6 | print "There's a giant bear here eating a cheese cake. What do you do?" 7 | print "1. Take the cake." 8 | print "2. Scream at the bear." 9 | 10 | bear = raw_input("> ") 11 | 12 | if bear == "1": 13 | print "The bear eats your face off. Good job!" 14 | elif bear == "2": 15 | print "The bear eats your legs off. Good job!" 16 | else: 17 | print "Well, doing %s is probably better. Bear runs away." % bear 18 | 19 | elif door == "2": 20 | print "You stare into the endless abyss at Cthulu's retina." 21 | print "1. Blueberries." 22 | print "2. Yellow jacket clothespins." 23 | print "3. Understanding revolvers yelling melodies." 24 | 25 | insanity = raw_input("> ") 26 | 27 | if insanity == "1" or insanity == "2": 28 | print "Your body survives powered by a mind of jello. Good job!" 29 | else: 30 | print "The insanity rot your eyes into a pool of muck. Good job!" 31 | 32 | else: 33 | print "You stumble around and fall on a knife and die. Good job!" -------------------------------------------------------------------------------- /sd30.py: -------------------------------------------------------------------------------- 1 | # Assign 30 to the variable people 2 | people = 30 3 | # Assign 40 to the variable cars 4 | cars = 40 5 | # Assign 15 to the variable trucks 6 | trucks = 15 7 | 8 | 9 | # If cars is greater than people display "We should take the cars." 10 | if cars > people: 11 | print "We should take the cars." 12 | # Else if cars is less than people display "We should not take the cars." 13 | elif cars < people: 14 | print "We should not take the cars." 15 | # Else display "We can't decide" 16 | else: 17 | print "We can't decide." 18 | 19 | # If trucks is greater than cars display "That's too many trucks." 20 | if trucks > cars: 21 | print "That's too many trucks." 22 | # Else if trucks is less than cars display "Maybe we could take the trucks." 23 | elif trucks < cars: 24 | print "Maybe we could take the trucks." 25 | # Else display "We still can't decide." 26 | else: 27 | print "We still can't decide." 28 | 29 | # If people is greater than trucks display "Alright, let's just take the trucks." 30 | if people > trucks: 31 | print "Alright, let's just take the trucks." 32 | # Else display "Fine, let's stay home then." 33 | else: 34 | print "Fine, let's stay home then." -------------------------------------------------------------------------------- /sd33.py: -------------------------------------------------------------------------------- 1 | numbers = [] 2 | increments = 0 3 | 4 | def sd1(r): 5 | i = 0 6 | while i < r: 7 | print "At the top i is %d" % i 8 | numbers.append(i) 9 | 10 | i = i + 1 11 | print "Numbers now: ", numbers 12 | print "At the bottom i is %d" % i 13 | 14 | 15 | def sd3(r, increments): 16 | i = 0 17 | while i < r: 18 | print "At the top i is %d" % 1 19 | numbers.append(i) 20 | 21 | i += increments 22 | print "Numbers now: ", numbers 23 | print "At the bottom i is %d" % i 24 | 25 | 26 | def sd5(r): 27 | for i in range(0, r): 28 | print "At the top i is %d" % i 29 | numbers.append(i) 30 | 31 | print "Numbers now: ", numbers 32 | print "At the bottom i is %d" % i 33 | 34 | print "\nCall function for study drill 1 with 6 as its argument" 35 | sd1(6); 36 | print "The numbers: " 37 | 38 | for num in numbers: 39 | print num 40 | 41 | numbers = [] # Empty the list 42 | print "\nCall function for study drill 3 with 6 and 2 as arguments" 43 | sd3(6, 2) 44 | print "The numbers: " 45 | 46 | for num in numbers: 47 | print num 48 | 49 | numbers = [] # Empty the list 50 | print "\nCall function for study drill 5 with 6 as its argument" 51 | sd5(6) 52 | print "The numbers: " 53 | 54 | for num in numbers: 55 | print num -------------------------------------------------------------------------------- /ex15/sd15.py: -------------------------------------------------------------------------------- 1 | # Import the argv method from the sys module 2 | from sys import argv 3 | 4 | # Assign the arguments in the argument variable 5 | # to the variables script and filename 6 | script, filename = argv 7 | 8 | # Call the method open with filename as its argument 9 | # and assign the result to the variable txt 10 | txt = open(filename) 11 | 12 | # Insert the variable filename into the 13 | # string format and display the string 14 | print "Here's your file %r:" % filename 15 | # Call the method read with no arguments on 16 | # the txt variable and display its contents 17 | print txt.read() 18 | 19 | # Call the method close with no arguments on the variable txt 20 | txt.close() 21 | 22 | # Display a string 23 | print "Type the filename again:" 24 | # Prompt the user to insert the filename 25 | # and assign the input to file_again 26 | file_again = raw_input("> ") 27 | 28 | # Call the method open with file_again as its argument 29 | # assign the result to the variable txt_again 30 | txt_again = open(file_again) 31 | 32 | # Call the method read with no arguments on the 33 | # variable txt_again and display its contents 34 | print txt_again.read() 35 | 36 | # Call the method close with no arguments on the variable txt_again 37 | txt_again.close() -------------------------------------------------------------------------------- /ex3.py: -------------------------------------------------------------------------------- 1 | # print the string "I will now count my chickens" 2 | print "I will now count my chickens:" 3 | 4 | # Calculate and print the number of hens 5 | print "Hens", 25.0 + 30.0 / 6.0 6 | # Calculate and print the nubmer of roosters 7 | print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 8 | 9 | # Print the string "Now I will count the eggs" 10 | print "Now I will count the eggs:" 11 | 12 | # Calculate and print the number of eggs 13 | print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 14 | 15 | # Print a string 16 | print "Is it true that 3 + 2 < 5 - 7?" 17 | 18 | # Calculate and print the answer to 3 + 2 < 5 - 7 19 | print 3.0 + 2.0 < 5.0 - 7.0 20 | 21 | # Calculate and print the answer to 3 + 2 22 | print "What is 3 + 2?", 3.0 + 2.0 23 | # Calculate and print the answer to 5 - 7 24 | print "What is 5 - 7?", 5.0 - 7.0 25 | 26 | # Print the string "Oh, that's why it's False." 27 | print "Oh, that's why it's False." 28 | 29 | # Print the string "What about some more." 30 | print "How about some more." 31 | 32 | # Print the string "Is it greater?" and calculate and print 5 > -2 33 | print "Is it greater?", 5.0 > -2.0 34 | # Print the string "Is it greater or equal?" and calculate 5 >= -2 35 | print "Is it greater or equal?", 5.0 >= -2.0 36 | # Print the string "Is it less or equal?" and calculate 5 <= -2 37 | print "Is it less or equal?", 5.0 <= -2.0 -------------------------------------------------------------------------------- /ex4.py: -------------------------------------------------------------------------------- 1 | cars = 100 # Assign 100 to the variable cars 2 | space_in_a_car = 4.0 # Assign 4.0 to the variable space_in_a_car 3 | drivers = 30 # Assign 30 to the variable drivers 4 | passengers = 90 # Assign 90 to the variable passengers 5 | # Subtract drivers from cars and Assgin the 6 | # result to the variable cars_not_driven 7 | cars_not_driven = cars - drivers 8 | cars_driven = drivers # Assign drivers to the variable cars_driven 9 | # Multiply cars_driven by space_in_a_car 10 | # and Assign the result to carpool_capacity 11 | carpool_capacity = cars_driven * space_in_a_car 12 | # Divide passengers by cars_driven and assign 13 | # the result to average_passengers_per_car 14 | average_passengers_per_car = passengers / cars_driven 15 | 16 | # Display the number of cars available 17 | print "There are", cars, "cars available." 18 | # Display the number of drivers available 19 | print "There are only", drivers, "drivers available." 20 | # Display the number of cars not driven today 21 | print "There will be", cars_not_driven, "empty cars today." 22 | # Display todays carpool capacity 23 | print "We can transport", carpool_capacity, "people today." 24 | # Display the number of passengers today 25 | print "We have", passengers, "to carpool today." 26 | # Display the average passengers per car 27 | print "We need to put about", average_passengers_per_car, "in each car." -------------------------------------------------------------------------------- /sd6_1.py: -------------------------------------------------------------------------------- 1 | # Assign a formatted string to the variable x 2 | x = "There are %d types of people." % 10 3 | # Assign the string "binary" to the variable binary 4 | binary = "binary" 5 | # Assign the string "don't" to the variable do_not 6 | do_not = "don't" 7 | # Insert the string binary and the string do_not into the 8 | # formatted string and assign the result to the variable y 9 | 10 | # Display the contents of the variable x 11 | print x 12 | # Display the contents of the variable y 13 | print y 14 | 15 | # Insert the variable x in to a formatted string and display its contents 16 | print "I said: %r." % x 17 | # Insert the variable y in to a formatted string and display its contents 18 | print "I also said: '%s'." % y 19 | 20 | # Assign the boolean False to the variable hilarious 21 | hilarious = False 22 | # Assign the formatted string to the variable joke_evaluation 23 | joke_evaluation = "Isn't that joke so funny?! %r" 24 | 25 | # Insert the boolean hilarious into the variable 26 | # joke_evaluation and display its contents 27 | print joke_evaluation % hilarious 28 | 29 | # Assign a string to the variable w 30 | w = "This is the left side of..." 31 | # Assign a string to the variable e 32 | e = "a string with a right side" 33 | 34 | # Concatenate the string in the variable e into the 35 | # string in the variable w and display its contents 36 | print w + e -------------------------------------------------------------------------------- /ex14.py: -------------------------------------------------------------------------------- 1 | # Import the argv method from the sys module 2 | from sys import argv 3 | 4 | # Assign the arguments in the arguement variable to 5 | # the variables script and user_name respectively 6 | script, user_name = argv 7 | # Assign the character '>' to the prompt variable 8 | prompt = '> ' 9 | 10 | # Insert the variables user_name and script 11 | # into the string format and display the string 12 | print "Hi %s, I'm the %s script." % (user_name, script) 13 | # Display a string 14 | print "I'd like to ask you a few questions." 15 | # Insert the variable user_name into the 16 | # formatted string and display the string 17 | print "Do you like me %s?" % user_name 18 | # Prompt the user for input and assign the input to the variable likes 19 | likes = raw_input(prompt) 20 | 21 | # Insert the variable user_name into the 22 | # formatted string and display the string 23 | print "Where do you live %s?" % user_name 24 | # Prompt the user for input and assign the input to the variable lives 25 | lives = raw_input(prompt) 26 | 27 | # Display the string 28 | print "What kind of computer do you have?" 29 | # Prompt the user for input and assign the input to the variable computer 30 | computer = raw_input(prompt) 31 | 32 | # Insert the variables likes, lives and computer 33 | # into the mutiline format string and display the string 34 | print """ 35 | Alright, so you said %r about liking me. 36 | You live in %r. Not sure where that is. 37 | And you have a %r computer. Nice. 38 | """ % (likes, lives, computer) -------------------------------------------------------------------------------- /sd7.py: -------------------------------------------------------------------------------- 1 | # Display the string "Mary had a little lamb" 2 | print "mary had a little lamb" 3 | # Display the formatted string "Its fleece was white as %s." 4 | # after inserting the string 'snow' 5 | print "Its fleece was white as %s." % 'snow' 6 | # Display the string "And everywhere that Mary went." 7 | print "And everywhere that Mary went." 8 | # Display the string "." ten times on the same line 9 | print "." * 10 # what'd that do? 10 | 11 | end1 = "C" # Assign the string "C" to the variable end1 12 | end2 = "h" # Assign the string "h" to the variable end2 13 | end3 = "e" # Assign the string "e" to the variable end3 14 | end4 = "e" # Assign the string "e" to the variable end4 15 | end5 = "s" # Assign the string "s" to the variable end5 16 | end6 = "e" # Assign the string "e" to the variable end6 17 | end7 = "B" # Assign the string "B" to the variable end7 18 | end8 = "u" # Assign the string "u" to the variable end8 19 | end9 = "r" # Assign the string "r" to the variable end9 20 | end10 = "g" # Assign the string "g" to the variable end10 21 | end11 = "e" # Assign the string "e" to the variable end11 22 | end12 = "r" # Assign the string "r" to the variable end12 23 | 24 | # watch that comma at the end. try removing it to see what happens 25 | # Concatenate the variables end1, end2, end3, end4, end5, and end6 26 | # Concatenate the variables end7, end8, end9, end10, end11, and end12 27 | # And Display them on the same line 28 | print end1 + end2 + end3 + end4 + end5 + end6, 29 | print end7 + end8 + end9 + end10 + end11 + end12 -------------------------------------------------------------------------------- /ex19.py: -------------------------------------------------------------------------------- 1 | # Create a cheese_and crackers function that takes two arguments 2 | def cheese_and_crackers(cheese_count, boxes_of_crackers): 3 | # Insert the first argument into a formatted string and display it 4 | print "You have %d cheese!" % cheese_count 5 | # Insert the second argument into a formatted string and display it 6 | print "You have %d boxes of crackers!" % boxes_of_crackers 7 | # Display a string 8 | print "Man that's enough for a party!" 9 | # Display a string with a new line character at the end 10 | print "Get a blanket.\n" 11 | 12 | 13 | # Display a string 14 | print "We can just give the function numbers directly:" 15 | # Call the cheese_and_crackers function with numbers 16 | cheese_and_crackers(20, 30) 17 | 18 | # Display a string 19 | print "Or, we can use variables from our script:" 20 | # Assign the number 10 to the variable amount_of_cheese 21 | amount_of_cheese = 10 22 | # Assign the number 50 to the variable amount_of_crackers 23 | amount_of_crackers = 50 24 | 25 | # Call the cheese_and_crackers function using variables 26 | cheese_and_crackers(amount_of_cheese, amount_of_crackers) 27 | 28 | 29 | # Display a string 30 | print "We can even do math inside too:" 31 | # Call the cheese_and_crackers function with math 32 | cheese_and_crackers(10 + 20, 5 + 6) 33 | 34 | 35 | # Display a string 36 | print "And we can combine the two, variables and math:" 37 | # Call the cheese_and_crackers function with math, numbers and variables 38 | cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 100) -------------------------------------------------------------------------------- /ex42.py: -------------------------------------------------------------------------------- 1 | ## Animal is-a object (yes, sort of confusing) look at the extra credit 2 | class Animal(object): 3 | pass 4 | 5 | ## Dog is-s Animal 6 | class Dog(Animal): 7 | 8 | def __init__(self, name): 9 | ## Dog has-a name 10 | self.name = name 11 | 12 | ## Cat is-a Animal 13 | class Cat(Animal): 14 | 15 | def __init__(self, name): 16 | ## Cat has-a name 17 | self.name = name 18 | 19 | ## Person is-a object 20 | class Person(object): 21 | 22 | def __init__(self, name): 23 | ## Person has-a name 24 | self.name = name 25 | 26 | ## Person has-a pet of some kind 27 | self.pet = name 28 | 29 | ## Employee is-a Person 30 | class Employee(Person): 31 | 32 | def __init__(self, name, salary): 33 | ## Employee has-a name which it inherits from Person 34 | super(Employee, self).__init__(name) 35 | ## Employee has-a salary 36 | self.salary = salary 37 | 38 | ## Fish is-a object 39 | class Fish(object): 40 | pass 41 | 42 | ## Salmon is-a Fiah 43 | class Salmon(Fish): 44 | pass 45 | 46 | ## Halibut is-a Fish 47 | class Halibut(Fish): 48 | pass 49 | 50 | 51 | ## rover is-a Dog 52 | rover = Dog("Rover") 53 | 54 | ## satan is-a Cat 55 | satan = Cat("Satan") 56 | 57 | ## mary is-a Person 58 | mary = Person("Mary") 59 | 60 | ## mary has-a pet satan 61 | mary.pet = satan 62 | 63 | ## frank is-a Employee, frank has-a salary of 120000 64 | frank = Employee("Frank", 120000) 65 | 66 | ## frank has-a pet rover 67 | frank.pet = rover 68 | 69 | ## flipper is an instance of Fish() 70 | flipper = Fish() 71 | 72 | ## crouse is an instance of Salmon() 73 | croush = Salmon() 74 | 75 | ## harry is an instance of Halibut() 76 | harry = Halibut() -------------------------------------------------------------------------------- /ex39.py: -------------------------------------------------------------------------------- 1 | # create a mapping of state to abbreviation 2 | states = { 3 | 'Oregon': 'OR', 4 | 'Florida': 'FL', 5 | 'California': 'CA', 6 | 'New York': 'NY', 7 | 'Michigan': 'MI' 8 | } 9 | 10 | # create a basic set of states and some cities in them 11 | cities = { 12 | 'CA': 'San Francisco', 13 | 'MI': 'Detroit', 14 | 'FL': 'Jacksonville' 15 | } 16 | 17 | # add some more cities 18 | cities['NY'] = 'New York' 19 | cities['OR'] = 'Portland' 20 | 21 | # print out some cities 22 | print '-' * 10 23 | print "NY State has: ", cities['NY'] 24 | print "OR State has: ", cities['OR'] 25 | 26 | # print some states 27 | print '-' * 10 28 | print "Michigan's abbreviation is: ", states['Michigan'] 29 | print "Florida's abbreviation is: ", states['Florida'] 30 | 31 | # do it by using the state then cities dict 32 | print '-' * 10 33 | print "Michigan has: ", cities[states['Michigan']] 34 | print "Florida has: ", cities[states['Florida']] 35 | 36 | # print every state abbreviation 37 | print '-' * 10 38 | for state, abbrev in states.items(): 39 | print "%s is abbreviated %s" % (state, abbrev) 40 | 41 | # print every city in state 42 | print '-' * 10 43 | for abbrev, city in cities.items(): 44 | print "%s has the city %s" % (abbrev, city) 45 | 46 | # now do both at the same time 47 | print '-' * 10 48 | for state, abbrev in states.items(): 49 | print "%s state is abbreviated %s and has city %s" % ( 50 | state, abbrev, cities[abbrev]) 51 | 52 | print '-' * 10 53 | # safely get a abbreviation by state that might not be there 54 | state = states.get('Texas') 55 | 56 | if not state: 57 | print "Sorry, no Texas." 58 | 59 | # get a city with a default value 60 | city = cities.get('TX', 'Does Not Exist') 61 | print "The city for the state 'TX' is: %s" % city -------------------------------------------------------------------------------- /ex35.py: -------------------------------------------------------------------------------- 1 | from sys import exit 2 | 3 | def gold_room(): 4 | print "This room is full of gold. How much do you take?" 5 | 6 | choice = raw_input("> ") 7 | if "0" in choice or "1" in choice: 8 | how_much = int(choice) 9 | else: 10 | dead("Man, learn to type a number.") 11 | 12 | if how_much < 50: 13 | print "Nice, you're not greedy, you win!" 14 | exit(0) 15 | else: 16 | dead("You greedy bastard!") 17 | 18 | 19 | def bear_room(): 20 | print "There is a bear here." 21 | print "The bear has a bunch of honey." 22 | print "The fat bear is in front of another door." 23 | print "How are you going to move the bear?" 24 | bear_moved = False 25 | 26 | while True: 27 | choice = raw_input("> ") 28 | 29 | if choice == "take honey": 30 | dead("The bear looks at you then slaps your face off.") 31 | elif choice == "taunt bear" and not bear_moved: 32 | print "The bear has moved from the door. You can go through it now." 33 | bear_moved = True 34 | elif choice == "taunt_bear" and bear_moved: 35 | dead("The bear gets pissed off and chews your leg off.") 36 | elif choice == "open door" and bear_moved: 37 | gold_room() 38 | else: 39 | print "I got no idea what that means." 40 | 41 | 42 | def cthulhu_room(): 43 | print "Here you seee the great evil Cthulhu." 44 | print "He, it, whatever stares at you and you go insane." 45 | print "Do you flee for your life or eat your head?" 46 | 47 | choice = raw_input("> ") 48 | 49 | if "flee" in choice: 50 | start() 51 | elif "head" in choice: 52 | dead("Well that was tasty!") 53 | else: 54 | cthulhu_room() 55 | 56 | 57 | def dead(why): 58 | print why, "Good job!" 59 | exit(0) 60 | 61 | def start(): 62 | print "You are in a dark room." 63 | print "There is a door to your right and left." 64 | print "Which one do you take?" 65 | 66 | choice = raw_input("> ") 67 | 68 | if choice == "left": 69 | bear_room() 70 | elif choice == "right": 71 | cthulhu_room() 72 | else: 73 | dead("You stumble around the room until you starve.") 74 | 75 | 76 | start() -------------------------------------------------------------------------------- /ex20/sd20.py: -------------------------------------------------------------------------------- 1 | # Import the function argv from the sys module 2 | from sys import argv 3 | 4 | # Assight the argument variables to 5 | # the variables script and input_file 6 | script, input_file = argv 7 | 8 | # Create a function named print_all that takes one argument 9 | # call the read function on the argument and display its contents 10 | def print_all(f): 11 | print f.read() 12 | 13 | # Create a function named rewind that takes one argument call the 14 | # seek function on the argument to return to the start of the file 15 | def rewind(f): 16 | f.seek(0) 17 | 18 | # Create a function named print_a_line that takes two arguments. 19 | # Display the first argument. Calls the readline function on 20 | # the second argument and displays it contents 21 | def print_a_line(line_count, f): 22 | print line_count, f.readline() 23 | 24 | # Call the open function with the variable input_file and 25 | # assign the result to the variable current_file 26 | current_file = open(input_file) 27 | 28 | # Diaplay a string and start a new line 29 | print "First let's print the whole file:\n" 30 | 31 | # Call the print_all function with the variable current_file 32 | print_all(current_file) 33 | 34 | # Display a string 35 | print "Now let's rewind, kind of like a tape." 36 | 37 | # Call the rewind function with the variable current_file 38 | rewind(current_file) 39 | 40 | # Display a string 41 | print "Let's print three lines:" 42 | 43 | # Assign the number 1 to the variable current line 44 | current_line = 1 45 | # Call the print_a_line function with the variables 46 | # current_line and current_file 47 | print_a_line(current_line, current_file) 48 | 49 | # Add 1 to the variable current_line 50 | current_line += 1 51 | # Call the print_a_line function with the 52 | # variables current_line and current_file 53 | print_a_line(current_line, current_file) 54 | 55 | # Add 1 to the variable current_line 56 | current_line += 1 57 | # Call the print_a_line function with the 58 | # variables current_line and current_file 59 | print_a_line(current_line, current_file) -------------------------------------------------------------------------------- /oop_test.py: -------------------------------------------------------------------------------- 1 | import random 2 | from urllib import urlopen 3 | import sys 4 | 5 | WORD_URL = "http://learncodethehardway.org/words.txt" 6 | WORDS = [] 7 | 8 | PHRASES = { 9 | "class %%%(%%%):": 10 | "Make a class named %%% that is-a %%%.", 11 | "class %%%(object):\n\tdef __init__(self, ***)": 12 | "class %%% has-a __init__ that takes self and *** parameters.", 13 | "class %%%(object):\n\tdef ***(self, @@@)": 14 | "class %%% has-a function named *** that takes self and @@@ parameters.", 15 | "*** = %%%()": 16 | "Set *** to an instance of class %%%.", 17 | "***.***(@@@)": 18 | "From *** get the *** function, and call it with parameters self, @@@.", 19 | "***.*** = '***'": 20 | "From *** get the *** attribute and set it to '***'." 21 | } 22 | 23 | # do they want to drill phreses first 24 | if len(sys.argv) == 2 and sys.argv[1] == "english": 25 | PHRASE_FIRST = True 26 | else: 27 | PHRASE_FIRST = False 28 | 29 | # load up the words from the website 30 | for word in urlopen(WORD_URL).readlines(): 31 | WORDS.append(word.strip()) 32 | 33 | 34 | def convert(snippet, phrase): 35 | class_names = [w.capitalize() for w in 36 | random.sample(WORDS, snippet.count("%%%"))] 37 | other_names = random.sample(WORDS, snippet.count("***")) 38 | results = [] 39 | param_names = [] 40 | 41 | for i in range(0, snippet.count("@@@")): 42 | param_count = random.randint(1, 3) 43 | param_names.append(', '.join(random.sample(WORDS, param_count))) 44 | 45 | for sentence in snippet, phrase: 46 | result = sentence[:] 47 | 48 | # fake class names 49 | for word in class_names: 50 | result = result.replace("%%%", word, 1) 51 | 52 | # fake other names 53 | for word in other_names: 54 | result = result.replace("***", word, 1) 55 | 56 | # fake parameter lists 57 | for word in param_names: 58 | result = result.replace("@@@", word, 1) 59 | 60 | results.append(result) 61 | 62 | return results 63 | 64 | 65 | # keep going until they hit CTRL-D 66 | try: 67 | while True: 68 | snippets = PHRASES.keys() 69 | random.shuffle(snippets) 70 | 71 | for snippet in snippets: 72 | phrase = PHRASES[snippet] 73 | question, answer = convert(snippet, phrase) 74 | if PHRASE_FIRST: 75 | question, answer = answer, question 76 | 77 | print question 78 | 79 | raw_input("> ") 80 | print "ANSWER: %s\n\n" % answer 81 | except EOFError: 82 | print "\nBye" -------------------------------------------------------------------------------- /sd39.py: -------------------------------------------------------------------------------- 1 | # create a mapping of provinces to abbreviation 2 | provinces = { 3 | 'Alberta': 'AB', 4 | 'British Columbia': 'BC', 5 | 'Manitoba': 'MB', 6 | 'New Brunswick': 'NB', 7 | 'Newfoundland and Labrador': 'NL', 8 | 'Nova Scotia': 'NS', 9 | 'Northwest Territories': 'NT', 10 | 'Nunavut': 'NU', 11 | 'Ontario': 'ON', 12 | 'Prince Edward Island': 'PE', 13 | 'Quebec': 'QC', 14 | 'Saskatchewan': 'SK', 15 | 'Yukon': 'YT' 16 | } 17 | 18 | # create a basic set of states and some cities in them 19 | cities = { 20 | 'AB': 'Edmonton', 21 | 'BC': 'Victoria', 22 | 'MB': 'Winnipeg', 23 | 'NB': 'Frederiction', 24 | 'NL': 'St. John\'s', 25 | 'NS': 'Halifax', 26 | 'NT': 'Yellowknife', 27 | 'NU': 'Iqaluit', 28 | 'ON': 'Toronto', 29 | 'PE': 'Charlottetown' 30 | } 31 | 32 | # add some more cities 33 | cities['QC'] = 'Quebec City' 34 | cities['SK'] = 'Regina' 35 | cities['YT'] = 'Whitehorse' 36 | 37 | # print out some cities 38 | print '-' * 10 39 | print "ON Province has: ", cities['ON'] 40 | print "BC Province has: ", cities['BC'] 41 | print "QC Province has: ", cities['QC'] 42 | 43 | # print out some provinces 44 | print '-' * 10 45 | print "British Columbia's abbreviation is: ", provinces['British Columbia'] 46 | print "Nova Scotia's abbreviation is: ", provinces['Nova Scotia'] 47 | print "Prince Edward Island's abbreviation is: ", provinces['Prince Edward Island'] 48 | 49 | # do it by using the province then cities dict 50 | print '-' * 10 51 | print "Ontario has: ", cities[provinces["Ontario"]] 52 | print "Quebec has: ", cities[provinces["Quebec"]] 53 | print "Alberta has: ", cities[provinces["Alberta"]] 54 | 55 | # print every province abbreviation 56 | print '-' * 10 57 | for province, abbrev in provinces.items(): 58 | print "%s is abbreviated %s" % (province, abbrev) 59 | 60 | # print every city in province 61 | print '-' * 10 62 | for abbrev, city in cities.items(): 63 | print "%s has the city %s" % (abbrev, city) 64 | 65 | # now do both at the same time 66 | print '-' * 10 67 | for province, abbrev in provinces.items(): 68 | print "%s province is abbreviated %s and has city %s" % ( 69 | province, abbrev, cities[abbrev]) 70 | 71 | print '-' * 10 72 | # safely get a abbreviation by province that might not be there 73 | province = provinces.get('Texas') 74 | 75 | if not province: 76 | print "Sorry, no Texas." 77 | 78 | # get a city with a default value 79 | city = cities.get('TX', 'Does Not Exist') 80 | print "The city for the state 'TX' is: %s" % city -------------------------------------------------------------------------------- /ex26.py: -------------------------------------------------------------------------------- 1 | def break_words(stuff): 2 | """This function will break up words for us.""" 3 | words = stuff.split(' ') 4 | return words 5 | 6 | def sort_words(words): 7 | """Sorts the words.""" 8 | return sorted(words) 9 | 10 | def print_first_word(words): 11 | """Prints the first word after popping it off.""" 12 | word = words.pop(0) 13 | print word 14 | 15 | def print_last_word(words): 16 | """Prints the last word after popping it off.""" 17 | word = words.pop(-1) 18 | print word 19 | 20 | def sort_sentence(sentence): 21 | """Takes in a full sentence and returns the sorted words.""" 22 | words = break_words(sentence) 23 | return sort_words(words) 24 | 25 | def print_first_and_last(sentence): 26 | """Prints the first and last words of the sentence.""" 27 | words = break_words(sentence) 28 | print_first_word(words) 29 | print_last_word(words) 30 | 31 | def print_first_and_last_sorted(sentence): 32 | """Sorts the words then prints the first and last one.""" 33 | words = sort_sentence(sentence) 34 | print_first_word(words) 35 | print_last_word(words) 36 | 37 | 38 | print "Let's practice everything." 39 | print 'You\'d need to know \'bout escapes with \\ that do \nnewlines and \ttabs.' 40 | 41 | poem = """ 42 | \tThe lovely world 43 | with logic so firmly planted 44 | cannot discern \nthe needs of love 45 | nor comprehend passion from intuition 46 | and requires an explantion 47 | \n\t\twhere there is none. 48 | """ 49 | 50 | 51 | print "--------------" 52 | print poem 53 | print "--------------" 54 | 55 | five = 10 - 2 + 3 - 6 56 | print "This should be five: %s" % five 57 | 58 | def secret_formula(started): 59 | jelly_beans = started * 500 60 | jars = jelly_beans / 1000 61 | crates = jars / 100 62 | return jelly_beans, jars, crates 63 | 64 | 65 | start_point = 10000 66 | beans, jars, crates = secret_formula(start_point) 67 | 68 | print "With a starting point of: %d" % start_point 69 | print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 70 | 71 | start_point = start_point / 10 72 | 73 | print "We can also do that this way:" 74 | print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) 75 | 76 | 77 | sentence = "All good things come to those who weight." 78 | 79 | words = break_words(sentence) 80 | sorted_words = sort_words(words) 81 | 82 | print_first_word(words) 83 | print_last_word(words) 84 | print_first_word(sorted_words) 85 | print_last_word(sorted_words) 86 | sorted_words = sort_sentence(sentence) 87 | print sorted_words 88 | 89 | print_first_and_last(sentence) 90 | 91 | print_first_and_last_sorted(sentence) -------------------------------------------------------------------------------- /ex43.py: -------------------------------------------------------------------------------- 1 | from sys import exit 2 | from random import randint 3 | 4 | class Scene(object): 5 | 6 | def enter(self): 7 | print "This scene is not yet confirgured. Subclass is and implement enter()." 8 | exit(1) 9 | 10 | class Engine(object): 11 | 12 | def __init__(self, scene_map): 13 | self.scene_map = scene_map 14 | 15 | def play(self): 16 | current_scene = self.scene_map.opening_scene() 17 | last_scene = self.scene_map.next_scene('finished') 18 | 19 | while current_scene != last_scene: 20 | next_scene_name = current_scene.enter() 21 | current_scene = self.scene_map.next_scene(next_scene_name) 22 | 23 | # be sure to print out the last scene 24 | current_scene.enter() 25 | 26 | class Death(Scene): 27 | 28 | quips = [ 29 | "You died. You kinda suck at this.", 30 | "Your mom would be proud...if she were smarter.", 31 | "Such a luser.", 32 | "I have a small puppy that's better at this." 33 | ] 34 | 35 | def enter(self): 36 | print Death.quips[randint(0, len(self.quips)-1)] 37 | exit(1) 38 | 39 | class CentralCorridor(Scene): 40 | 41 | def enter(self): 42 | print "The Gothans of Planet Percal #25 have invaded your ship and distroyed" 43 | print "your entire crew. You are the last surviving member and your last" 44 | print "mission is to get the neutron destruct bomb from the Weapons Armory," 45 | print "put it in the bridge, and blow the ship up after getting into an " 46 | print "escape pod." 47 | print "\n" 48 | print "You're running down the central corridor to the Weapons Armory when" 49 | print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" 50 | print "flowing around his hate filled body. He's blocking the door to the" 51 | print "Armory and about to pull a weapon to blast you." 52 | 53 | action = raw_input("> ") 54 | 55 | if action == "shoot!": 56 | print "Quick on the draw you yank out you blaster and fire it at the Gothon." 57 | print "His clown costume is flowing and moving around his body, which throws" 58 | print "off your aim. Your laser hits his costume but misses him entirely. This" 59 | print "completely ruins his brand new costume his mother bought him, which" 60 | print "makes him fly into an insane rage and blast you repeatedly in the face until" 61 | print "you are dead. Then he eats you." 62 | return 'death' 63 | 64 | elif action == 'dodge!': 65 | print "Like a world class boxer you dodge, weave, slip and slide right" 66 | print "as the Gothon's blaster cranks a laser past your head." 67 | print "In the middle of your artful dodge your foot slips and you" 68 | print "bang you head on the metal wall and pass out." 69 | print "You wake up shortly after only to die as the Gothon stomps on" 70 | print "your head and eats you." 71 | return 'death' 72 | 73 | elif action == "tell a joke": 74 | print "Lucky for you they made you learn Gothon insults in the academy." 75 | print "You tell the one Gothon joke you know:" 76 | print "Lbhe zbgure vf fb sng, jura fur fvgf nebnaq gur ubhfr, fur fvgf nebhaq gur ubhfr." 77 | print "The Gothon stops, tries not to laugh, then busts out laughing and can't move." 78 | print "While he's laughing you run up and shoot him square in the head" 79 | print "puttng him down, then jump through the Weapons Armory door." 80 | return 'laser_weapn_armory' 81 | 82 | else: 83 | print "DOES NOT COMPUTE!" 84 | return 'central_corridor' 85 | 86 | class LaserWeaponArmory(Scene): 87 | 88 | def enter(self): 89 | print "You do a dive roll into the Weapons Armory, crouch and scan the room" 90 | print "for more Gothons that might be hiding. It's dead quiet, too quiet." 91 | print "You stand up and run to the far side of the room and find the" 92 | print "neutron bomb in its container. There's a keypad lock on the box" 93 | print "and you need the code to get the bomb out. If you get the code" 94 | print "wrong 10 times then the lock closes forever and you can't" 95 | print "get the bomb. The code is 3 digits." 96 | code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) 97 | guess = raw_input("[keypad]> ") 98 | guesses = 0 99 | 100 | while guess != code and guesses < 10: 101 | print "BZZZZEDDD!" 102 | guesses += 1 103 | guess = raw_input("[keypad]> ") 104 | 105 | if guess == code: 106 | print "The container clicks open and the seal breaks, letting gas out." 107 | print "You grab the neutron bomb and run as fast as you can to the" 108 | print "bridge where you must place it in the right spot." 109 | return 'the_bridge' 110 | else: 111 | print "The lock buzzes one last time and then you hear a sickening" 112 | print "melting sound as the mechanism is fused together." 113 | print "You decide to sit there, and finally the Gothons blow up the" 114 | print "ship from their ship and you die." 115 | return 'death' 116 | 117 | class TheBridge(Scene): 118 | 119 | def enter(self): 120 | print "You burst onto the Bridge with the netron destruct bomb" 121 | print "under your arm and surprise 5 Gothons who are trying to" 122 | print "take control of the ship. Each of them has an even uglier" 123 | print "clown costume than the last. They haven't pulled their" 124 | print "weapons out yet, as they see the active bomb under your" 125 | print "arm and don't want to set it off." 126 | 127 | action = raw_input("> ") 128 | 129 | if action == "throw the bomb": 130 | print "In a panic you throw the bomb at the group of Gothons" 131 | print "and make a leap for the door. Right as you drop it a" 132 | print "Gothon shoots you right in the back killing you." 133 | print "As you die you see another Gothon frantically try to disarm" 134 | print "the bomb. You die knowing they will probably blow up when" 135 | print "it goes off." 136 | return 'death' 137 | 138 | elif action == "slowly place the bomb": 139 | print "You point your blaster at the bomb under your arm" 140 | print "and the Gothons put their hands up and start to sweat." 141 | print "You inch backward to the door, open it, and then carefully" 142 | print "place the bomb on the floor, pointing your blaster at it." 143 | print "You then jump back through the door, punch the close button" 144 | print "and blast the lock so the Gothons can't get out." 145 | print "Now that the bomb is placed you run to the escape pad to" 146 | print "get off this tin can." 147 | return 'escape_pod' 148 | else: 149 | print "DOES NOT COMPUTE!" 150 | return 'the_bridge' 151 | 152 | class EscapePod(Scene): 153 | 154 | def enter(self): 155 | print "You rush through the ship desperately trying to make it to" 156 | print "the escape pod before the whole ship explodes. It seems like" 157 | print "hardly any Gothons are on the ship, so your run is clear of" 158 | print "interference. You get to the chamber with the escape pods, and" 159 | print "now need to pick one to take. Some of them could be damaged" 160 | print "but you don't have time to look. There's 5 pods, which one" 161 | print "do you take?" 162 | 163 | good_pod = randint(1,5) 164 | guess = raw_input("[pod #]> ") 165 | 166 | 167 | if int(guess) != good_pod: 168 | print "You jump into pod %s and hit the eject button." % guess 169 | print "The pod escapes out into the void of space, then" 170 | print "implodes as the hull ruptures, crushing your body" 171 | print "into jam jelly." 172 | return 'death' 173 | else: 174 | print "You jump into pod %s and hit the eject button." % guess 175 | print "The pod easily slides out into space heading to" 176 | print "the planet below. As it fires to the planet, you look" 177 | print "back and seee your ship implode then explode like a" 178 | print "bright star, taking out the Gothon ship at the same" 179 | print "time. You won!" 180 | 181 | return 'finished' 182 | 183 | class Finished(Scene): 184 | 185 | def enter(self): 186 | print "You won! Good job." 187 | return 'finished' 188 | 189 | class Map(object): 190 | 191 | scenes = { 192 | 'central_corridor': CentralCorridor(), 193 | 'laser_weapn_armory': LaserWeaponArmory(), 194 | 'the_bridge': TheBridge(), 195 | 'escape_pod': EscapePod(), 196 | 'death': Death(), 197 | 'finished': Finished(), 198 | } 199 | 200 | def __init__(self, start_scene): 201 | self.start_scene = start_scene 202 | 203 | def next_scene(self, scene_name): 204 | val = Map.scenes.get(scene_name) 205 | return val 206 | 207 | def opening_scene(self): 208 | return self.next_scene(self.start_scene) 209 | 210 | 211 | a_map = Map('central_corridor') 212 | a_game = Engine(a_map) 213 | a_game.play() --------------------------------------------------------------------------------