├── .DS_Store ├── README.md ├── dungeon_game.py ├── ex ├── ex10.py ├── ex11.py ├── ex12.py ├── ex13.py ├── ex14.py ├── ex15.py ├── ex15_sample.rtf ├── ex16.py ├── ex17.py ├── ex18.py ├── ex19.py ├── ex20.py ├── ex21.py ├── ex24.py ├── ex25.py ├── ex25.pyc ├── ex26.py ├── ex29.py ├── ex3.py ├── ex30.py ├── ex31.py ├── ex32.py ├── ex33.py ├── ex34.py ├── ex35.py ├── ex36.py ├── ex38.py ├── ex39.py ├── ex40.py ├── ex41.py ├── ex42.py ├── ex43.py ├── ex5.py ├── ex6.py ├── ex7.py ├── ex8.py ├── ex9.py ├── github_test.py ├── new_file.txt ├── program.py ├── test.py ├── test.txt └── word_count.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrdbourke/LearnPythonTheHardWay/d414a2be5b1d2002c1a793dd68316da4166005d0/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Learn Python the Hard Way 2 | 3 | This repo is for all the challenge files created within the book Learning Python the Hard Way by Zed Shaw. 4 | -------------------------------------------------------------------------------- /dungeon_game.py: -------------------------------------------------------------------------------- 1 | TILES = ('-', ' ', '-', ' ', '-', '||', 2 | '_', '|', '_', '|', '_', '|', '||', 3 | '&', ' ', '_', ' ', '||', 4 | ' ', ' ', ' ', '^', ' ', '||' 5 | ) 6 | 7 | for item in TILES: 8 | if item == '||': 9 | print() #print() prints out on a new line by default 10 | else: 11 | print(item, end="") 12 | -------------------------------------------------------------------------------- /ex: -------------------------------------------------------------------------------- 1 | formatter = "%r %r %r %r" 2 | 3 | print formatter % (1, 2, 3, 4) 4 | print formatter % ("one", "two", "three", "four") 5 | print formatter % (True, False, False, True) 6 | print formatter % (formatter, formatter, formatter, formatter) 7 | print formatter % ( 8 | "I had this thing." 9 | "That you could type up right." 10 | "But it didn't sing." 11 | "So I said goodnight." 12 | ) 13 | -------------------------------------------------------------------------------- /ex10.py: -------------------------------------------------------------------------------- 1 | tabby_cat = "\tI'm tabbed in." 2 | persian_cat = "I'm split\non a line." 3 | backslash_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 backslash_cat 15 | print fat_cat 16 | 17 | #while True: 18 | #for i in ["/","-","|","\\","|"]: 19 | #print "%s\r" % i, 20 | -------------------------------------------------------------------------------- /ex11.py: -------------------------------------------------------------------------------- 1 | """ 2 | print "How old are you?", 3 | age = raw_input() 4 | print "How tall are you?", 5 | height = raw_input() 6 | print "How much do you weigh?", 7 | weight = raw_input() 8 | 9 | print "So you're %r old, %r tall and %r heavy." % ( 10 | age, height, weight) 11 | """ 12 | 13 | print "What is your name?", 14 | name = raw_input() 15 | print "What is your favourite food?", 16 | food = raw_input() 17 | print "Where is your favourite restaurant?", 18 | restaurant = raw_input() 19 | 20 | print "%r loves to eat %r and his favourite restaurant is %r." % ( 21 | name, food, restaurant 22 | ) 23 | -------------------------------------------------------------------------------- /ex12.py: -------------------------------------------------------------------------------- 1 | age = raw_input("How old are you? ") 2 | height = raw_input("How tall are you? ") 3 | weight = raw_input("How much do you weight? ") 4 | 5 | print "So, you're %r old, %r tall and %r heavy." % ( 6 | age, height, weight 7 | ) 8 | -------------------------------------------------------------------------------- /ex13.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script, first, second, third = argv 4 | 5 | print "The script is called:", script 6 | print "Your first variable is:", first 7 | print "Your second variable is:", second 8 | print "Your third variable is:", third 9 | print "What is your name?", 10 | name = raw_input() 11 | -------------------------------------------------------------------------------- /ex14.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script, user_name, age = argv 4 | 5 | prompt = '... ' 6 | 7 | print "Hi %s, I'm the %s script." % (user_name, script) 8 | print "I'd like to ask you a few questions." 9 | print "Do you like me %s?" % user_name 10 | likes = raw_input(prompt) 11 | 12 | print "Where do you live %s?" % user_name 13 | lives = raw_input(prompt) 14 | 15 | print "When did you turn %s?" % age 16 | month = raw_input(prompt) 17 | 18 | print "What kind of computer do you have?" 19 | computer = raw_input(prompt) 20 | 21 | print """ 22 | Alright, so you said %r about liking me. 23 | You live in %r. Not sure where that is. 24 | Your birthday is in %r. 25 | And you have a %r computer. Nice. 26 | """ % (likes, lives, month, computer) 27 | -------------------------------------------------------------------------------- /ex15.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | #This tells that the first word of argv is the script (ex15.py) 3 | #The second part of argv (argv[1]) is the filename 4 | script, filename = argv 5 | 6 | #This sets up the txt variable to open the previously entered filename 7 | txt = open(filename) 8 | 9 | #This prints the filename 10 | print "Here's your file %r:" % filename 11 | #Using the .read() function the file is read 12 | print txt.read() 13 | 14 | txt.close() 15 | 16 | 17 | #The user is asked for the filename again (same name as before) 18 | print "Type the filename again:" 19 | file_again = raw_input("> ") 20 | 21 | #This sets txt_again to the second filename that the user entered 22 | txt_again = open(file_again) 23 | 24 | #This reads the second entering of the filename and prints the contents 25 | print txt_again.read() 26 | 27 | txt_again.close() 28 | -------------------------------------------------------------------------------- /ex15_sample.rtf: -------------------------------------------------------------------------------- 1 | {\rtf1\ansi\ansicpg1252\cocoartf1504\cocoasubrtf820 2 | {\fonttbl\f0\fswiss\fcharset0 Helvetica;} 3 | {\colortbl;\red255\green255\blue255;} 4 | {\*\expandedcolortbl;;} 5 | \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 6 | \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 7 | 8 | \f0\fs24 \cf0 This is stuff I typed into a file.\ 9 | It is really cool stuff.\ 10 | Lots and lots of fun to have in here. } -------------------------------------------------------------------------------- /ex16.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | #the filename is the argument variable 4 | #enter into terminal, python script filename 5 | script, filename = argv 6 | 7 | #Asking the user whether or not they want to erase the file 8 | print "We're going to erase %r." % filename 9 | print "If you don't want that, hit CTRL-C (^C)." 10 | print "If you do want that, hit RETURN." 11 | 12 | #Asking for input from the user, any input will do, we are just after the return key 13 | raw_input("?") 14 | 15 | #opens the specified file given to argv 16 | print "Opening the file..." 17 | #"w" mode creates the file if it does not exist and empties it if it does 18 | target = open(filename, 'w') 19 | 20 | #deleting the contents of the file, because of the w, this step isn't 100% needed 21 | print "Truncating the file. Goodbye!" 22 | target.truncate() 23 | 24 | print "Now I'm going to ask you for three lines." 25 | 26 | #gathering input from the user 27 | line1 = raw_input("line 1: ") 28 | line2 = raw_input("line 2: ") 29 | line3 = raw_input("line 3: ") 30 | 31 | print "I'm going to write these to the file." 32 | 33 | #writing the input from the user to the specified file 34 | target.write("%s\n%s\n%s\n" % (line1, line2, line3)) 35 | ''' 36 | target.write("\n") 37 | target.write(line2) 38 | target.write("\n") 39 | target.write(line3) 40 | target.write("\n") 41 | ''' 42 | #closing the file and telling the user about it 43 | print "And finally, we close it." 44 | target.close() 45 | -------------------------------------------------------------------------------- /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 | #checks whether or not the output file exists 15 | print "Does the output file exist? %r" % exists(to_file) 16 | print "Ready, hit RETURN to continue, CTRL-C to abort." 17 | raw_input() 18 | 19 | #opens the out_file and clears it, then it writes data to it 20 | out_file = open(to_file, 'w').write(indata) 21 | #out_file.write(indata) 22 | 23 | print "Alright, all done." 24 | 25 | out_file.close() 26 | in_file.close() 27 | -------------------------------------------------------------------------------- /ex18.py: -------------------------------------------------------------------------------- 1 | def print_two(*args): 2 | arg1, arg2, = args 3 | print "arg1: %r, arg2: %r" % (arg1, arg2) 4 | 5 | def print_two_again(arg1, arg2): 6 | print "arg1: %r, arg2: %r" % (arg1, arg2) 7 | 8 | def print_one(arg1): 9 | print "arg1: %r" % arg1 10 | 11 | def print_none(): 12 | print "I got nothin'." 13 | 14 | print_two("Zed", "Shaw") 15 | print_two_again("Zed", "Shaw") 16 | print_one("First!") 17 | print_none() 18 | -------------------------------------------------------------------------------- /ex19.py: -------------------------------------------------------------------------------- 1 | #defining the function cheese_and_crackers, with the arguments 2 | #cheese_count and cheese_and_crackers 3 | def cheese_and_crackers(cheese_count, boxes_of_crackers): 4 | print "You have %d cheeses!" % cheese_count 5 | print "You have %d boxes of crackers!" % boxes_of_crackers 6 | print "Man that's enough for a party!" 7 | print "Get a blanket.\n" 8 | 9 | #feeding cheese_and_crackers two values as arguments 10 | print "We can just give the function numbers directly:" 11 | cheese_and_crackers(20, 30) 12 | 13 | #creating variables for amount_of_cheese and amount_of_crackers 14 | print "OR, we can use variables from our script:" 15 | amount_of_cheese = 10 16 | amount_of_crackers = 50 17 | 18 | #feeding the cheese_and_crackers function the previously created variables 19 | cheese_and_crackers(amount_of_cheese, amount_of_crackers) 20 | 21 | #feeding the cheese_and_crackers function math as the arguments 22 | print "We can even do math inside too:" 23 | cheese_and_crackers(10 + 20, 5 + 6) 24 | 25 | #combining the variables with math as arguments 26 | print "And we can combine the two, variables and math:" 27 | cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) 28 | 29 | def weightlifting(sets, reps): 30 | print "You have to do %d sets and %d reps of squats!" % (sets, reps) 31 | print "Don't do anything less than %d reps!" % reps 32 | print "Man you're going to make some gains!" 33 | print "Keep on lifting!\n" 34 | 35 | weightlifting(5, 10) 36 | weightlifting(5*2, 1*8) 37 | weightlifting(16/4, 10/5) 38 | amount_of_sets = 10 39 | amount_of_reps = 10 40 | weightlifting(amount_of_sets, amount_of_reps) 41 | weightlifting(amount_of_sets - 7, amount_of_reps) 42 | weightlifting(amount_of_sets - 6, amount_of_reps + 2) 43 | -------------------------------------------------------------------------------- /ex20.py: -------------------------------------------------------------------------------- 1 | #imports the argument variable 2 | from sys import argv 3 | #states what the argv is going to be 4 | script, input_file = argv 5 | 6 | #creating a function to print all within f 7 | def print_all(f): 8 | print f.read() 9 | 10 | #seek starts reading the file at a specific point 11 | #seek(0) will start at the beginning of the file 12 | def rewind(f): 13 | f.seek(0) 14 | 15 | #creating a function to print a line which takes two arguments 16 | def print_a_line(line_count, f): 17 | print line_count, f.readline() 18 | 19 | #creating a variable current_file that opens the input_file given to the script 20 | current_file = open(input_file) 21 | 22 | print "First let's print the whole file:\n" 23 | 24 | #printing the contents of the current_file 25 | print_all(current_file) 26 | 27 | print "Now let's rewind, kind of like a tape." 28 | 29 | #taking the current_file back to the start using seek(0) 30 | rewind(current_file) 31 | 32 | print "Let's print three lines:" 33 | 34 | #adding 1 to the current_line twice and then printing the current line of the file 35 | current_line = 1 36 | print_a_line(current_line, current_file) 37 | 38 | current_line += 1 39 | print_a_line(current_line, current_file) 40 | 41 | current_line += 1 42 | print_a_line(current_line, current_file) 43 | -------------------------------------------------------------------------------- /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 | print "Let's do some math with just functions!" 18 | 19 | age = add(30, 5) 20 | height = subtract(78, 4) 21 | weight = multiply(90, 2) 22 | iq = divide(100, 2) 23 | 24 | print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) 25 | 26 | #A puzzle for the extra credit, type it in anyway. 27 | 28 | print "Here is a puzzle." 29 | 30 | what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) 31 | 32 | print "That becomes: ", what, "Can you do it by hand?" 33 | 34 | question = multiply(iq, add(height, divide(age, subtract(weight, 1023)))) 35 | 36 | print "That becomes: ", question,"." 37 | -------------------------------------------------------------------------------- /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 an explanation 10 | \n\t\twhere there is none. 11 | """ 12 | 13 | print "-------------" 14 | print poem 15 | print "-------------" 16 | 17 | five = 10 - 2 + 3 - 6 18 | print "This should be five: %s" % five 19 | 20 | def secret_formula(started): 21 | jelly_beans = started * 500 22 | jars = jelly_beans / 1000 23 | crates = jars / 100 24 | return jelly_beans, jars, crates 25 | 26 | start_point = 10000 27 | beans, jars, crates = secret_formula(start_point) 28 | 29 | print "With a starting point of: %d" % start_point 30 | print "We'd have %d beans, %d jars and %d crates." % (beans, jars, crates) 31 | 32 | start_point = start_point / 10 33 | 34 | print "We can also do that this way:" 35 | print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) 36 | -------------------------------------------------------------------------------- /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) 36 | -------------------------------------------------------------------------------- /ex25.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrdbourke/LearnPythonTheHardWay/d414a2be5b1d2002c1a793dd68316da4166005d0/ex25.pyc -------------------------------------------------------------------------------- /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 \n newlines and \t tabs.' 40 | 41 | poem = """ 42 | \tThe lovely world 43 | with logic so firmly planted 44 | cannot discern \n the 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 | start_point = 10000 65 | jelly_beans, jars, crates = secret_formula(start_point) 66 | 67 | print "With a starting point of: %d" % start_point 68 | print "We'd have %d beans, %d jars, and %d crates." % (jelly_beans, jars, crates) 69 | 70 | start_point = start_point / 10 71 | 72 | print "We can also do that this way:" 73 | print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) 74 | 75 | sentence = "All good\tthings come to those who wait." 76 | 77 | words = break_words(sentence) 78 | sorted_words = sort_words(words) 79 | 80 | print_first_word(words) 81 | print_last_word(words) 82 | print_first_word(sorted_words) 83 | print_last_word(sorted_words) 84 | sorted_words = sort_sentence(sentence) 85 | print(sorted_words) 86 | 87 | print_first_and_last(sentence) 88 | 89 | print_first_and_last_sorted(sentence) 90 | -------------------------------------------------------------------------------- /ex29.py: -------------------------------------------------------------------------------- 1 | people = 20 2 | cats = 30 3 | dogs = 15 4 | 5 | if people < cats: 6 | print "Too many cats! The world is doomed!" 7 | 8 | if people > cats: 9 | print "Not many cats! The world is saved!" 10 | 11 | if people < dogs: 12 | print "The world is drooled on!" 13 | 14 | if people > dogs: 15 | print "The world is dry!" 16 | 17 | dogs += 5 18 | 19 | if people >= dogs: 20 | print "People are greater than or equal to dogs." 21 | 22 | if people <= dogs: 23 | print "People are less than or equal to dogs." 24 | 25 | if people == dogs: 26 | print "People are dogs." 27 | 28 | if people == dogs and cats > people: 29 | print "People are dogs and cats rule over people." 30 | 31 | if people is not None: 32 | print "I'm a dog person." 33 | -------------------------------------------------------------------------------- /ex3.py: -------------------------------------------------------------------------------- 1 | #Number of cars 2 | cars = 100 3 | #Amount of space in a car 4 | space_in_a_car = 4.0 5 | #Number of drivers 6 | drivers = 30 7 | #Number of passengers 8 | passengers = 90 9 | #Amount of cars not driven 10 | cars_not_driven = cars - drivers 11 | #Number of cars that are driven 12 | cars_driven = drivers 13 | #The amount of people who can be carpooled 14 | carpool_capacity = cars_driven * space_in_a_car 15 | #The average number of passengers per car 16 | average_passengers_per_car = passengers / cars_driven 17 | 18 | print "There are", cars, "cars available." 19 | print "There are only", drivers, "drivers available." 20 | print "There will be", cars_not_driven, "empty cars today." 21 | print "We can transport", carpool_capacity, "people today." 22 | print "We have", passengers, "to carpool today." 23 | print "We need to put about", average_passengers_per_car, "in each car." 24 | -------------------------------------------------------------------------------- /ex30.py: -------------------------------------------------------------------------------- 1 | people = 10 2 | cars = 45 3 | trucks = 97 4 | 5 | if cars > people: 6 | #prints if cars greater than people 7 | print "We should take the cars." 8 | elif cars < people: 9 | #prints if cars not greater than people 10 | print "We should not take the cars." 11 | else: 12 | print "We can't decide." 13 | 14 | if trucks > cars or trucks > people: 15 | #prints if trucks greater than cars or trucks greater than people 16 | print "That's too many trucks." 17 | elif trucks < cars: 18 | #prints if cars greater than trucks 19 | print "Maybe we could take the trucks." 20 | else: 21 | print "We still can't decide." 22 | 23 | if people > trucks or cars < people: 24 | #prints if people greater than trucks or cars less than people 25 | print "Alright, let's just take the trucks." 26 | else: 27 | print "Fine, let's stay home then." 28 | -------------------------------------------------------------------------------- /ex31.py: -------------------------------------------------------------------------------- 1 | print "You enter a dark room with two doors. Do you go through door #1, #2 or #3?" 2 | 3 | door = raw_input("> ") 4 | 5 | if door == "1": 6 | print "There's a giant bear here eat 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 Cthulhu'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 rots your eyes into a pool of muck. Good job!" 31 | 32 | elif door == "3": 33 | print "You found a treasure chest! It's full of over $5 billion!" 34 | print "1. Take the gold for yourself." 35 | print "2. Share the wealth with others and only keep 10%." 36 | 37 | gold = raw_input("> ") 38 | 39 | if gold == "1": 40 | print "Your greed summons the keepers of the gold, the gold vanishe in" 41 | print "front of your eyes before burning them, sending you blind." 42 | 43 | elif gold == "2": 44 | print "Your generosity summons the keepers of the gold, they give you" 45 | print "an extra $1 billion to keep for yourself." 46 | 47 | else: 48 | print "So you're just going to leave the chest alone??" 49 | else: 50 | print "You stumble around and fall on a knife and die. Good job!" 51 | -------------------------------------------------------------------------------- /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 through a list 6 | 7 | for number in the_count: 8 | print "This is count %d" % number 9 | 10 | #same as above 11 | 12 | for fruit in fruits: 13 | print "This is count %d" % number 14 | 15 | # also we can go through mixed lists too 16 | # notice we have to use %r since we don't know what's in it 17 | for i in change: 18 | print "I got %r" % i 19 | 20 | # we can also build lists, frist start with an empty one 21 | elements = [] 22 | 23 | # then use the range function to do 0 to 5 counts 24 | # range creates a number range from 0 to 6, it will print 0 to 5 25 | 26 | ''' 27 | for i in range(0, 6): 28 | print "Adding %d to the list." % i 29 | #append is a function that lists understand 30 | elements.append(i) 31 | ''' 32 | 33 | elements.append(range(0,6)) 34 | 35 | # now we can print them out too 36 | for i in elements: 37 | print "Element was: %r" % i 38 | -------------------------------------------------------------------------------- /ex33.py: -------------------------------------------------------------------------------- 1 | def for_loop(loop_variable, increment): 2 | i = 0 3 | numbers = range(0, loop_variable) 4 | 5 | for number in numbers: 6 | if number <= loop_variable: 7 | print "At the top i is %d" % i 8 | numbers.append(i) 9 | 10 | i = i + increment 11 | print "Numbers now: ", numbers 12 | print "At the bottom i is %d" % i 13 | 14 | print "The numbers: " 15 | 16 | for num in numbers: 17 | print num 18 | 19 | for_loop(30, 10) 20 | -------------------------------------------------------------------------------- /ex34.py: -------------------------------------------------------------------------------- 1 | animal = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] 2 | 3 | print animal[1] 4 | print animal[2] 5 | print animal[0] 6 | print animal[3] 7 | print animal[2] 8 | print animal[5] 9 | print animal[4] 10 | -------------------------------------------------------------------------------- /ex35.py: -------------------------------------------------------------------------------- 1 | from sys import exit 2 | 3 | choice = 0 4 | 5 | #broken 6 | def choice_zero(): 7 | choice = 0 8 | choice = raw_input("> ") 9 | 10 | def gold_room(): 11 | print "This room is full of gold. How much do you take?" 12 | 13 | how_much = int(raw_input("> ")) 14 | if how_much < 50: 15 | print "Nice, you're not greedy, you win!" 16 | exit(0) 17 | else: 18 | dead("You greedy bastard!") 19 | 20 | #broken (because of choice()) 21 | def bear_room(): 22 | print "There is a bear here." 23 | print "The bear has a bunch of honey." 24 | print "The fat bear is in front of another door." 25 | print "How are you going to move the bear?" 26 | bear_moved = False 27 | 28 | while True: 29 | choice_zero() 30 | if choice == "honey" or choice == "honey pot": 31 | dead("The bear looks at you then slaps your face off.") 32 | elif "taunt" or "taunt bear" in choice and not bear_moved: 33 | print "The bear has moved from the door. You can go through it." 34 | bear_moved = True 35 | choice_zero() 36 | elif choice == "taunt bear" and bear_moved: 37 | dead("The bear gets pissed off and chews your leg off.") 38 | elif "open" or "open door" or "go" or "go through door" and bear_moved: 39 | gold_room() 40 | else: 41 | print "I got no idea what that means." 42 | 43 | def cthulhu_room(): 44 | print "Here you see the great evil Cthulhu." 45 | print "He, it, whatever stares at you and you go insane." 46 | print "Do you flee for your life or eat your head?" 47 | 48 | choice = raw_input("> ") 49 | 50 | if "flee" in choice: 51 | start() 52 | elif "head" in choice: 53 | dead("Well that was tasty!") 54 | else: 55 | cthulhu_room() 56 | 57 | 58 | def dead(why): 59 | print why, "Good job!" 60 | exit(0) 61 | 62 | def start(): 63 | print "You are in a dark room." 64 | print "There is a door to your right and left." 65 | print "Which one do you take?" 66 | 67 | choice = raw_input("> ") 68 | 69 | if choice == "left": 70 | bear_room() 71 | elif choice == "right": 72 | cthulhu_room() 73 | else: 74 | dead("You stumble around the room until you starve.") 75 | 76 | def end_game(): 77 | leave = raw_input('> ') 78 | 79 | if leave or exit or finish or end in leave: 80 | exit(0) 81 | else: 82 | gold_room() 83 | 84 | start() 85 | -------------------------------------------------------------------------------- /ex36.py: -------------------------------------------------------------------------------- 1 | import random 2 | from sys import exit 3 | 4 | #defining the different outcomes of each of the functions 5 | leg_day_squats = ["3 sets of 10 squats", 6 | "3 sets of 10 lunges", 7 | "3 sets of 10 stiff-legged deadlifts", 8 | "3 sets of 10 box jumps"] 9 | 10 | leg_day_not_squats = ["3 sets of 10 leg press", 11 | "3 sets of 10 leg extension", 12 | "3 sets of 10 hamstring curl", 13 | "3 sets of 10 calf raises"] 14 | 15 | rest_day_message = "You've managed to unlock a rest day! \nEnjoy the day off for recovery." 16 | 17 | chest_day = ["3 sets of 10 bench press", 18 | "3 sets of 10 weighted dips", 19 | "3 sets of 10 chest pullovers", 20 | "3 sets of 10 tricep pressdowns"] 21 | 22 | back_day = ["3 sets of 10 bent over rows", 23 | "3 sets of 10 deadlifts", 24 | "3 sets of 10 pullups", 25 | "3 sets of 10 bicep curls"] 26 | 27 | #starting the workout bot functions here 28 | def start(): 29 | print "Hello world! I'm the workout bot!" 30 | print "It's time to make some gains!" 31 | print "Press 1 for leg day or 2 for an upper body workout." 32 | print "Or type in random for a random workout!" 33 | 34 | start_input = raw_input("> ") 35 | 36 | if start_input == "1": 37 | leg_day() 38 | elif start_input == "2": 39 | upper_body() 40 | elif start_input == "random": 41 | rand = random.randint(1,3) 42 | if rand == 1: 43 | leg_day() 44 | elif rand == 2: 45 | upper_body() 46 | elif rand == 3: 47 | rest_day() 48 | else: 49 | print "Something went wrong :(" 50 | else: 51 | print "I don't understand that!" 52 | 53 | 54 | def leg_day(): 55 | #leg day function, offer choice for squats or no squats 56 | print "Let's grow some wheels!" 57 | print "Do you prefer squats? Enter 1" 58 | print "No squats? Enter 2" 59 | print "Want an upper body workout instead? Enter upper" 60 | 61 | leg_day_input = raw_input("> ") 62 | 63 | if leg_day_input == "1": 64 | for item in leg_day_squats: 65 | print item 66 | elif leg_day_input == "2": 67 | for item in leg_day_not_squats: 68 | print item 69 | elif leg_day_input == "upper": 70 | upper_body() 71 | else: 72 | print "I'm sorry, I don't understand that!" 73 | restart() 74 | 75 | 76 | def upper_body(): 77 | #upper body day function, offer choice for chest or back workout 78 | print "Let's pump up that upper body!" 79 | print "Want to train chest? Hit 1" 80 | print "Back day more your thing? Hit 2" 81 | print "Prefer a leg day? Type in legs" 82 | 83 | upper_body_input = raw_input("> ") 84 | 85 | if upper_body_input == "1": 86 | for item in chest_day: 87 | print item 88 | elif upper_body_input == "2": 89 | for item in back_day: 90 | print item 91 | elif upper_body_input == "legs": 92 | leg_day() 93 | else: 94 | print "I'm sorry, I don't understand that!" 95 | restart() 96 | 97 | 98 | def rest_day(): 99 | #rest day function, print rest day message 100 | print rest_day_message 101 | restart() 102 | 103 | 104 | def restart(): 105 | #restart entire program back to start 106 | #set inputs to 0 107 | print "\nAwesome work!" 108 | print "When you've finished your workout or rest day, enter 1 to go back to the start." 109 | print "Or type any key to exit the workout bot." 110 | #implement exit option 111 | reset = raw_input("> ") 112 | if reset == "1": 113 | start() 114 | else: 115 | exit(0) 116 | 117 | start() 118 | -------------------------------------------------------------------------------- /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 | 7 | more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 8 | 9 | while len(stuff) != 10: 10 | next_one = more_stuff.pop() 11 | print "Adding: ", next_one 12 | stuff.append(next_one) 13 | print "There are %d items now." % len(stuff) 14 | 15 | print "There we go: ", stuff 16 | 17 | print "Let's do some things with stuff." 18 | 19 | print stuff[1] 20 | print stuff[-1] 21 | #call pop on stuff 22 | #can also be considered as pop.(stuff) - call pop with the argument stuff 23 | print stuff.pop() 24 | print ' '.join(stuff) 25 | print '#'.join(stuff[3:5]) 26 | -------------------------------------------------------------------------------- /ex39.py: -------------------------------------------------------------------------------- 1 | # create a mapping of state to abbreviation 2 | 3 | states = { 4 | 'Oregon': 'OR', 5 | 'Florida': 'FL', 6 | 'California': 'CA', 7 | 'New York': 'NY', 8 | 'Michigan': 'MI' 9 | } 10 | 11 | # create a basic set of states and some cities in them 12 | 13 | cities = { 14 | 'CA': 'San Francisco', 15 | 'MI': 'Detroit', 16 | 'FL': 'Jacksonville' 17 | } 18 | 19 | # add some more cities 20 | cities['NY'] = 'New York' 21 | cities['OR'] = 'Portland' 22 | 23 | #print out some cities 24 | print '-' * 10 25 | print "NY State has: ", cities['NY'] 26 | print "OR State has: ", cities['OR'] 27 | 28 | #print some states 29 | print '-' * 10 30 | print "Michigan's abbreviation is: ", states['Michigan'] 31 | print "Florida's abbreviation is: ", states['Florida'] 32 | 33 | # do it by using the state then cities dict 34 | print '-' * 10 35 | print "Michigan has: ", cities[states['Michigan']] 36 | print "Florida has: ", cities[states['Florida']] 37 | 38 | # print every state abbreviation 39 | print '-' * 10 40 | for state, abbrev in states.items(): 41 | print "%s is abbreviated %s" % (state, abbrev) 42 | 43 | #print every city in state 44 | print '-' * 10 45 | for abbrev, city in cities.items(): 46 | print "%s has the city %s" % (abbrev, city) 47 | 48 | # now do both at the same time 49 | print '-' * 10 50 | for state, abbrev in states.items(): 51 | print "%s state is abbreviated %s and has city %s" % ( 52 | state, abbrev, cities[abbrev]) 53 | 54 | print '-' * 10 55 | # safely get a abbreviation by state that might not be there 56 | state = states.get('Texas') 57 | 58 | if not state: 59 | print "Sorry, no Texas." 60 | 61 | # get a city with a default value 62 | city = cities.get('TX', 'Does Not Exist') 63 | print "The city for the state 'TX' is: %s" % city 64 | -------------------------------------------------------------------------------- /ex40.py: -------------------------------------------------------------------------------- 1 | lyrics = ["25 sitting on 25 mil"] 2 | 3 | class Song(object): 4 | 5 | def __init__(self, lyrics): 6 | self.lyrics = lyrics 7 | 8 | def sing_me_a_song(self): 9 | for line in self.lyrics: 10 | print line 11 | 12 | happy_bday = Song(["Happy birthday to you", 13 | "I don't want to get sued", 14 | "So I'll stop right there"]) 15 | 16 | bulls_on_parade = Song(["They rally around tha family", 17 | "With pockets full of shells"]) 18 | started_from_the_bottom = Song(["Started from the bottom", 19 | "Now we here", 20 | "Started from the bottom", 21 | "Now the whole teams freaking here"]) 22 | 23 | hyfr = Song(lyrics) 24 | 25 | happy_bday.sing_me_a_song() 26 | 27 | bulls_on_parade.sing_me_a_song() 28 | 29 | started_from_the_bottom.sing_me_a_song() 30 | 31 | hyfr.sing_me_a_song() 32 | -------------------------------------------------------------------------------- /ex41.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 phrases 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 | def convert(snippet, phrase): 34 | class_names = [w.capitalize() for w in 35 | random.sample(WORDS, snippet.count("%%%"))] 36 | other_names = random.sample(WORDS, snippet.count("***")) 37 | results = [] 38 | param_names = [] 39 | 40 | for i in range(0, snippet.count("@@@")): 41 | param_count = random.randint(1,3) 42 | param_names.append(', '.join(random.sample(WORDS, param_count))) 43 | 44 | for sentence in snippet, phrase: 45 | result = sentence[:] 46 | 47 | # fake class names 48 | for word in class_names: 49 | result = result.replace("%%%", word, 1) 50 | 51 | # fake other names 52 | for word in other_names: 53 | result = result.replace("***", word, 1) 54 | 55 | # fake parameter lists 56 | for word in param_names: 57 | result = result.replace("@@@", word, 1) 58 | 59 | results.append(result) 60 | 61 | return results 62 | 63 | 64 | 65 | # keep going until they hit CRTL-D 66 | 67 | try: 68 | while True: 69 | snippets = PHRASES.keys() 70 | random.shuffle(snippets) 71 | 72 | for snippet in snippets: 73 | phrase = PHRASES[snippet] 74 | question, answer = convert(snippet, phrase) 75 | if PHRASE_FIRST: 76 | question, answer = answer, question 77 | 78 | print question 79 | 80 | 81 | raw_input("> ") 82 | print "ANSWER: %s\n\n" %answer 83 | except EOFError: 84 | print "\nBye" 85 | -------------------------------------------------------------------------------- /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-a 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 | 20 | ## Person is-a object 21 | class Person(object): 22 | 23 | def __init__(self, name): 24 | ## Person has-a name 25 | self.name = name 26 | 27 | ## Person has-a pet of some kind 28 | self.pet = None 29 | 30 | ## Employee is-a Person 31 | class Employee(Person): 32 | 33 | def __init__(self, name, salary): 34 | ##Employee has a different name to person 35 | super(Employee, self).__init__(name) 36 | ## Employee has-a salary 37 | self.salary = salary 38 | 39 | ## Fish is-a object 40 | class Fish(object): 41 | pass 42 | 43 | ## Salmon is-a fish 44 | class Salmon(Fish): 45 | pass 46 | 47 | ## Halibut is-a fish 48 | class Halibut(Fish): 49 | pass 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 called satan 61 | mary.pet = satan 62 | 63 | ## Frank is-a Employee and 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-a fish 70 | flipper = Fish() 71 | 72 | ## Crouse is-a Salmon 73 | crouse = Salmon() 74 | 75 | ## Harry is-a Halibut 76 | harry = Halibut() 77 | -------------------------------------------------------------------------------- /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 configured." 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.open_scene() 17 | last_scene = self.scene_map.next_scene('finsihed') 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 | current_scene.enter() 24 | 25 | class Death(Scene): 26 | quips = [ 27 | "You died. You kinda suck at this.", 28 | "Your mom would be proud... if she were smarter.", 29 | "Such a luser.", 30 | "I have a small puppy that's better at this." 31 | ] 32 | 33 | def enter(self): 34 | print Death.quips[randint(0, len(self.quips)-1)] 35 | exit(1) 36 | 37 | class CentralCorridor(Scene): 38 | 39 | def enter(self): 40 | print "You're on a spaceship hurtling through space." 41 | print "Your goal is to get to the laser weapon armory." 42 | print "Once here you'll have to find a better weapon to defend yourself through" 43 | print "the rest of the ship. There's aliens on board who will try to kill" 44 | print "you." 45 | print "Your mission is to reach the escape pods are on the other side of the ship." 46 | print "There's a goblin in front of you, what do you do?" 47 | 48 | action = raw_input("> ") 49 | 50 | if action == "shoot": 51 | print "You try and shoot the goblin but miss...." 52 | return 'death' 53 | 54 | if action == "throw grenade": 55 | print "The goblin catches the grenade before eating it and burping" 56 | print "the debris back at you." 57 | return 'death' 58 | 59 | if action == "give cupcake": 60 | print "You give the goblin a cupcake. He becomes your friend." 61 | return 'laser_weapon_armory' 62 | 63 | else: 64 | print "DOES NOT COMPUTE" 65 | return 'central_corridor' 66 | 67 | 68 | class LaserWeaponArmory(Scene): 69 | 70 | def enter(self): 71 | print "You enter the weapons armory." 72 | print "There's a coded keypad on the weapons chest." 73 | print "The code changes every 30 seconds so hurry!" 74 | code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) 75 | print "Current code:" + code 76 | print "Enter the code before it changes, you've only got 1 try!" 77 | code_entry = raw_input("[keypad]> ") 78 | 79 | if code_entry == code: 80 | print "Code successful." 81 | print "You pick up the MAJOR LASER" 82 | return 'the_bridge' 83 | else: 84 | return 'death' 85 | 86 | class TheBridge(Scene): 87 | 88 | def enter(self): 89 | print "You manage to make it to the bridge of the ship." 90 | print "There's a hoard of goblins at the far end of the bridge." 91 | print "They're dumb so they don't know you're there yet." 92 | print "If they see you, you're dead. What should you do?" 93 | 94 | action = raw_input("> ") 95 | 96 | if action == "shoot": 97 | print "You don't manage to shoot them all at once, they end up eating you." 98 | return 'death' 99 | 100 | if action == "use MAJOR LASER": 101 | print "You charge the MAJOR LASER......!" 102 | print "The goblins stupidly line up in a single file." 103 | print "BOOOOOOM headshot!" 104 | print "You fire the laser and get a five headshot collateral!!!" 105 | return 'escape_pod' 106 | 107 | else: 108 | print "Your actions are futile. The dumb goblins spot you and ravage" 109 | print "your puny body." 110 | return 'death' 111 | 112 | class EscapePod(Scene): 113 | 114 | def enter(self): 115 | print "You see a whole bunch of escape pods in the room." 116 | print "There's three in front of you and 1 of them is damaged." 117 | print "If you pick the wrong one you're a goner...." 118 | print "Choose wisely!" 119 | 120 | action = int(raw_input("> ")) 121 | damaged_pod = randint(1,3) 122 | 123 | if action == damaged_pod: 124 | print "You chose the damaged pod! Catch ya later...." 125 | return 'death' 126 | else: 127 | print "Good choice! You escape at the speed of light back to your home planet." 128 | print "Catch ya later!" 129 | return 'finished' 130 | 131 | class Finished(Scene): 132 | 133 | def enter(self): 134 | print "Congratulations! You won the game!" 135 | return 'finished' 136 | 137 | 138 | class Map(object): 139 | 140 | scenes = { 141 | 'escape_pod' : EscapePod(), 142 | 'finished' : Finished(), 143 | 'the_bridge' : TheBridge(), 144 | 'central_corridor' : CentralCorridor(), 145 | 'laser_weapon_armory' : LaserWeaponArmory(), 146 | 'death' : Death(), 147 | } 148 | 149 | def __init__(self, start_scene): 150 | self.start_scene = start_scene 151 | 152 | def next_scene(self, scene_name): 153 | self.scene_name = scene_name 154 | 155 | def open_scene(self): 156 | return self.next_scene(self.start_scene) 157 | 158 | a_map = Map('central_corridor') 159 | a_game = Engine(a_map) 160 | a_game.play() 161 | -------------------------------------------------------------------------------- /ex5.py: -------------------------------------------------------------------------------- 1 | name = 'Zed Shaw' 2 | age = 35 # not a lie 3 | height = 74 # inches 4 | height_in_cm = height * 2.54 5 | weight = 180 # lbs 6 | weight_in_kg = weight / 2.2 7 | eyes = 'Blue' 8 | teeth = 'White' 9 | hair = 'Brown' 10 | 11 | print "Let's talk about %s." % name 12 | print "%d cm tall." % height_in_cm 13 | print "He's %d kilograms heavy." % weight_in_kg 14 | print "Actually that's not too heavy." 15 | print "He's got %s eyes and %s hair." % (eyes, hair) 16 | print "His teeth are usually %s depending on the coffee." % teeth 17 | 18 | # this line is tricky, try to get it exactly right 19 | 20 | print "If I add %d, %d, and %d I get %d." % ( 21 | age, height, weight, age + height + weight) 22 | -------------------------------------------------------------------------------- /ex6.py: -------------------------------------------------------------------------------- 1 | #defining the x variable 2 | x = "There are %d types of people." % 10 3 | #defining the binary variable 4 | binary = "binary" 5 | #defining the do_not variable 6 | do_not = "don't" 7 | #defining the y variable using a combination of the binary and do_not variables 8 | y = "Those who know %s and those who %s." % (binary, do_not) 9 | #displaying the previously defined x variable 10 | print x 11 | #displaying the previously defined y variable 12 | print y 13 | 14 | # %r prints all the details within a string, it displays raw data 15 | # %r is best for debugging 16 | print "I said: %r." % x 17 | #printing the y string 18 | print "I also said: '%s'." % y 19 | 20 | #defining hilarious as a False variable 21 | hilarious = False 22 | #Defining a joke evaluation statement 23 | joke_evaluation = "Isn't that joke so funny?! %r" 24 | 25 | #printing the joke evaluation string and result 26 | print joke_evaluation % hilarious 27 | 28 | #defining w as the left side of a string 29 | w = "This is the left side of..." 30 | #defining e as the right side of a string 31 | e = "a string with a right side." 32 | 33 | #printing a cominbation of w and e string variables 34 | print w + e 35 | -------------------------------------------------------------------------------- /ex7.py: -------------------------------------------------------------------------------- 1 | print "Mary had a little lamb." 2 | #snow is not a variable here, it is just a string with the word snow in it 3 | print "Its fleece was white as %s." % 'snow' 4 | print "And everywhere that May went." 5 | #printing 10 x . 6 | print "." * 10 # what'd that do? 7 | 8 | #Defining variables with the letters from the word Cheese Burger in them 9 | end1 = "C" 10 | end2 = "h" 11 | end3 = "e" 12 | end4 = "e" 13 | end5 = "s" 14 | end6 = "e" 15 | end7 = "B" 16 | end8 = "u" 17 | end9 = "r" 18 | end10 = "g" 19 | end11 = "e" 20 | end12 = "r" 21 | 22 | #watch that comma at the end. try removing it to see what happens 23 | #printing the strings with the letters from Cheese Burger 24 | #removing the comma causes the words to be printed on different lines 25 | print end1 + end2 + end3 + end4 + end5 + end6, 26 | print end7 + end8 + end9 + end10 + end11 + end12 27 | -------------------------------------------------------------------------------- /ex8.py: -------------------------------------------------------------------------------- 1 | formatter = "%r %r %r %r" 2 | 3 | print formatter % (1, 2, 3, 4) 4 | print formatter % ("one", "two", "three", "four") 5 | print formatter % (True, False, False, True) 6 | print formatter % (formatter, formatter, formatter, formatter) 7 | #The following strings are printed out with single quotes. Python tries to print 8 | #things in the most efficient way it can. 9 | print formatter % ( 10 | "I had this thing.", 11 | "That you could type up right.", 12 | "But it didn't sing.", 13 | "So I said goodnight." 14 | ) 15 | -------------------------------------------------------------------------------- /ex9.py: -------------------------------------------------------------------------------- 1 | days = "Mon Tue Wed Thu Fri Sat Sun" 2 | #\n prints the string on a new line each time 3 | #the months will be print each on a seperate line 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 | """ 15 | -------------------------------------------------------------------------------- /github_test.py: -------------------------------------------------------------------------------- 1 | print("Hello! What's your name and age?") 2 | 3 | name = input("> ") 4 | age = input("> ") 5 | 6 | def hello_word(name, age): 7 | print("Nice to meet you {}, I'm also {} years old.".format(name, age)) 8 | 9 | hello_word(name, age) 10 | -------------------------------------------------------------------------------- /new_file.txt: -------------------------------------------------------------------------------- 1 | This is a test file. 2 | -------------------------------------------------------------------------------- /program.py: -------------------------------------------------------------------------------- 1 | import sys 2 | print sys.argv 3 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | s = "Hello there".split() 2 | print(s) 3 | -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | This is a test file. 2 | -------------------------------------------------------------------------------- /word_count.py: -------------------------------------------------------------------------------- 1 | s = "Hi my name is Daniel and I love to jump over people with the name Daniel." 2 | 3 | def word_count(s): 4 | s_list = s.lower().split() 5 | dict_string = {} 6 | for word in s_list: 7 | count = s_list.count(word) 8 | dict_string =count[word] 9 | return dict_string 10 | 11 | word_count(s) 12 | --------------------------------------------------------------------------------