diff --git a/arg.py b/arg.py new file mode 100644 index 00000000000..92aa4139dbd --- /dev/null +++ b/arg.py @@ -0,0 +1,7 @@ +#!/usr/bin/python +from sys import argv +script,first,second,third = argv +print "the script is called:", script +print "your first variable is:", first +print "your second variable is:", second +print "your third variable is:", third diff --git a/cat.py b/cat.py new file mode 100644 index 00000000000..e1e01350b40 --- /dev/null +++ b/cat.py @@ -0,0 +1,37 @@ +#/usr/bin/python +#file name cat.py + +import sys + +def readfile (filename): + ''' Print a file to the standard output.''' + f = file(filename) + while True: + line = f.readline() + if len(line) == 0: + break + print line, #notice comma + f.close() +## Script starts from here + +if len(sys.argv) < 2: + print 'No action specified.' + sys.exit() +if sys.argv[1].startswith('--'): + option = sys.argv[1][2:] + if option == 'version': + print 'Version 1.2' + elif option == 'help': + print '''\ +This program prints files to the standard output. +Any number of files can be specified. +Options include: + --version : prints the version number + --help : Display this help''' + else: + print 'Unknow option.' + sys.exit() +else: + for filename in sys.argv[1:]: + readfile(filename) + diff --git a/ex15.py b/ex15.py new file mode 100644 index 00000000000..9f37ced2474 --- /dev/null +++ b/ex15.py @@ -0,0 +1,24 @@ +#!/usr/bin/python +from sys import argv +script,filename=argv +print "we're going to erase %r." % filename +print "If you don't want that, hit CTRL-C(^C)." +print "If you do want that, hit RETURN." +raw_input("?") +print "opening the file..." +target = open(filename, 'w') +print "Truncating the file. Goodbye!" +target.truncate() +print "Now I'm going to ask you for three lines." +line1=raw_input("line 1:") +line2=raw_input("line 2:") +line3=raw_input("line 3:") +print "I'm going to write these to the file." +target.write(line1) +target.write("\n") +target.write(line2) +target.write("\n") +target.write(line3) +target.write("\n") +print "and finally, we close it." +target.close() diff --git a/ex15.txt b/ex15.txt new file mode 100644 index 00000000000..06cb570cdc3 --- /dev/null +++ b/ex15.txt @@ -0,0 +1,3 @@ +abc1 +def2 +ghk3 diff --git a/ex17.py b/ex17.py new file mode 100644 index 00000000000..19e0e659bda --- /dev/null +++ b/ex17.py @@ -0,0 +1,16 @@ +#!/usr/bin/python +from sys import argv +from os.path import exists +script,from_file,to_file=argv +print "copying from %s to %s" %(from_file, to_file) +input =open (from_file) +indata=input.read() +print "the input file is %d bytes long" % len(indata) +print "does the output file exist? %r" % exists(to_file) +print "ready, hit RETURN to continue, CTRL-C to abort." +raw_input() +output=open(to_file,'w') +output.write(indata) +print "alright, all done" +output.close() +input.close() diff --git a/ex17.txt b/ex17.txt new file mode 100644 index 00000000000..06cb570cdc3 --- /dev/null +++ b/ex17.txt @@ -0,0 +1,3 @@ +abc1 +def2 +ghk3 diff --git a/ex18.py b/ex18.py new file mode 100644 index 00000000000..6063c5037d2 --- /dev/null +++ b/ex18.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +def print_two(*args): + arg1,arg2=args + print "arg1: %r, arg2: %r" % (arg1,arg2) +def print_two_again(arg1,arg2): + print "arg1: %r, arg2: %r" %(arg1, arg2) +def print_one(arg1): + print "arg1: %r" % arg1 +def print_none(): + print "I got nothing." + +print_two("zed", "shaw") +print_two_again("zed","shaw") +print_one("first!") +print_none() diff --git a/ex19.py b/ex19.py new file mode 100644 index 00000000000..ab7b77163a2 --- /dev/null +++ b/ex19.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +def cheese_and_crackers(cheese_count, boxes_of_crackers): + print "you have %d cheeses!" % (cheese_count) + print "you have %d boxes of crackers!" % boxes_of_crackers + print "man that's enough for a party!" + print "get a blanket.\n" +print "we can just give the function numbers directly:" +cheese_and_crackers(20,30) +print "OR, we can use variables from our script:" +amount_of_cheese=10 +amount_of_crackers=50 +cheese_and_crackers(amount_of_cheese,amount_of_crackers) +print "we can even do math inside too:" +cheese_and_crackers(10+20, 5+6) +print "we can combine the two, variables and math:" +cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) + + + + diff --git a/ex20.py b/ex20.py new file mode 100644 index 00000000000..eb8df241d54 --- /dev/null +++ b/ex20.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +from sys import argv +script, input_file=argv +def print_all(f): + print f.read() +def rewind(f): + f.seek(0) +def print_a_line(line_count, f): + print line_count, f.readline() +current_file=open(input_file) +print "first let's print the whole file:\n" +print_all(current_file) +print "now let's rewind, kind of like a tape." +rewind(current_file) +print "let's print three lines:" +current_line=1 +print_a_line(current_line, current_file) +current_line = current_line +1 +print_a_line(current_line, current_file) +current_line = current_line +1 +print_a_line(current_line, current_file) + diff --git a/ex21.py b/ex21.py new file mode 100644 index 00000000000..cf01abb7cca --- /dev/null +++ b/ex21.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +def add(a,b): + print "ADDING %d + %d" %(a,b) + return a+b +def subtract(a,b): + print "SUBTRACTING %d - %d" %(a,b) + return a-b +def multiply(a,b): + print "MULTIPLYING %d * %d" %(a,b) + return a*b +def divide(a,b): + print "DIVIDING %d / %d" %(a,b) + return a/b +print "Let's do some math with just functions!" +age = add(30,5) +height= subtract(78,4) +weight= multiply(90,2) +iq = divide(100,2) +print "Age: %d, Height: %d, Weight: %d, IQ: %d" %(age, height,weight, iq) +# A puzzle +print "Here is a puzzle." +what = add (age,subtract(height,multiply(weight,divide(iq,2)))) +print "that becames: %d, can you do it by hand?" %(what) + + diff --git a/ex24.py b/ex24.py new file mode 100644 index 00000000000..9661cf9dda6 --- /dev/null +++ b/ex24.py @@ -0,0 +1,29 @@ +#!/usr/bin/python +print "Let's practice everything." +print 'you\'d need to know \'bout eccapes with \\ that do \n newlines and \t tabs.' +poem = """ +\tthe lovely world +with logic so firmly planted +cannot discern \n the needs of love +nor comprehend passion from intuition +and requires an explanation +\n\t\twhere there is none. +""" + +print "----------------------" +print poem +print "----------------------" +five = 10 -2 +3 -6 +print "this should be five: %s" %five +def secret_formula(started): + jelly_beans=started * 500 + jars=jelly_beans / 100 + crates=jars / 100 + return jelly_beans, jars,crates +start_point = 10000 +beans, jars, crates = secret_formula(start_point) +print "with a starting point of: %d" % start_point +print "we'd have %d beans, %d jars, and %d crates." %(beans, jars, crates) +start_point = start_point / 10 +print "we can also do that this way:" +print "we'd have %d beans, %d jars, and %d crates." %secret_formula(start_point) diff --git a/ex25.py b/ex25.py new file mode 100644 index 00000000000..72cca3c5ace --- /dev/null +++ b/ex25.py @@ -0,0 +1,30 @@ +#!/usr/bin/python +def break_words(stuff): + """this function will break up words for us.""" + words = stuff.split(' ') + return words +def sort_words(words): + """sorts the words.""" + return sorted(words) +def print_first_word(words): + """prints the first word after popping it off.""" + word = words.pop(0) + print word +def print_last_word(words): + """prints the last word after popping it off.""" + word= words.pop(-1) + print word +def sort_sentence(sentence): + """takes in a full sentence and returns the sorted words.""" + words= break_words(sentence) + return sort_words(words) +def print_first_and_last(sentence): + """prints the first and last words of the sentence.""" + words = break_words(sentence) + print_first_word(words) + print_last_word(words) +def print_first_and_last_sorted(sentence): + """sorts the words then prints the first and last one.""" + words=sort_sentence(sentence) + print_first_word(words) + print_last_word(words) diff --git a/ex25.pyc b/ex25.pyc new file mode 100644 index 00000000000..70209a83599 Binary files /dev/null and b/ex25.pyc differ diff --git a/ex29.py b/ex29.py new file mode 100644 index 00000000000..4559ccdf2ae --- /dev/null +++ b/ex29.py @@ -0,0 +1,27 @@ +#!/usr/bin/python +people = 20 +cats = 30 +dogs = 15 + +if people < cats: + print "Too many cats! the world is doomed!" + +if people > cats: + print "Not many cats! the world is saved!" + +if people < dogs: + print "the world is drooled on!" + +if people > dogs: + print "the world is dry!" + +dogs += 5 + +if people >= dogs: + print "people are greater than or equal to dogs." + +if people <= dogs: + print "people are less than or equal to dogs." + +if people == dogs: + print "people are dogs." diff --git a/ex31.py b/ex31.py new file mode 100644 index 00000000000..c200da48da5 --- /dev/null +++ b/ex31.py @@ -0,0 +1,33 @@ +#!/usr/bin/python +print "you enter a dark room with two doors, do you go through door #1 or door #2?" + +door = raw_input("> ") + +if door == "1": + print "there's a giant bear here eating cheese cake. what do you do?" + print "1. take the cake." + print "2. scream at the bear." + + + bear = raw_input("> ") + if bear=="1": + print "the bear eats your face off. good job!" + elif bear == "2": + print "the bear eats your legs off. good job!" + else: + print "well, doing %s is probably better. bear runs away." % bear +elif door == "2": + print "your stare into the endless abyss at cthulhu's retina." + print "1. blueberries." + print "2. yellow jacket clothespins." + print "3. understanding revolvers yelling melodies." + + insanity = raw_input("> ") + + if insanity == "1" or insanity == "2": + print "your body survives powered by a mind of jello. good job!" + else: + print "the insanity rots your eyes into a pool of muck. good job!" + +else: + print "you sbumble around and fall on a knife and die. good job!" diff --git a/ex32.py b/ex32.py new file mode 100644 index 00000000000..330c49c9b37 --- /dev/null +++ b/ex32.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +the_count = [1,2,3,4,5] +fruits = ['apples','oranges''pears','apricots'] +change = [1, 'pennies', 2, 'dimes', 3,'quarters'] +# this first kind of for-loop goes through a list + +for number in the_count: + print "this is count %d" % number + +#same as above + +for fruit in fruits: + print "A fruit of type: %s" % fruit +for i in change: + print "I got %r" % i +#elements = [] + +#for i in range(0,6): +# print "adding %d to the list." %i +# elements.append(i) +elements = range(0,6) + +for i in elements: + print "element was: %d" % i + diff --git a/ex33.py b/ex33.py new file mode 100644 index 00000000000..882b135b8e4 --- /dev/null +++ b/ex33.py @@ -0,0 +1,13 @@ +#!/usr/bin/python +i = 0 +numbers = [] + +while i < 6: + print "at the top i is %d" % i + numbers.append(i) + i = i + 1 + print "numbers now:", numbers + print "at the bottom i is %d" %i +print "the numbers: " +for num in numbers: + print num diff --git a/ex34.py b/ex34.py new file mode 100644 index 00000000000..4b5be272762 --- /dev/null +++ b/ex34.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +from sys import exit + +def gold_room(): + print "This room is full of gold. How much do you take?" + next = raw_input("> ") + if "0" in next or "1" in next: + how_much = int(next) + else: + dead("Man, learn to type a number.") + + if how_much < 50: + print "Nice, you're not greedy, you win!" + exit(0) + else: + dead("you greedy bastard!") +def bear_room(): + print "there is a bear here." + print "the bear has a bunch of honey." + print "the fat bear is in front of another door." + print "how are you going to move the bear?" + bear_moved = False + + while True: + next = raw_input("> ") + + if next == "take honey": + dead("the bear looks at you then slaps your face off.") + elif next == "taunt bear" and not bear_moved: + print "the bear has moved from the door. you can go through it now." + bear_moved = True + elif next == "taunt bear" and bear_moved: + dead("the bear gets pissed off and chews your leg off.") + + elif next == "open door" and bear_moved: + gold_room() + else: + print "I got no idea what that means." + +def cthulhu_room(): + print "Here you see the great evil cthulhu." + print "he, it, whatever stares at you and you go insane." + print "do you flee for your life or eat your head?" + + next = raw_input("> ") + if "flee" in next: + start() + elif "head" in next: + dead("well that was tasty!") + else: + cthulhu_room() + +def dead(y): + print y, "good job!" + exit(0) + +def start(): + print "you are in a dark room." + print "there is a door to your right and left." + print "which one do you take?" + + next = raw_input("> ") + if next == "left": + bear_room() + elif next == "right": + cthulhu_room() + else: + dead("you stumble around the room until you starve.") + +start() diff --git a/ex39.py b/ex39.py new file mode 100644 index 00000000000..aa3311e3406 --- /dev/null +++ b/ex39.py @@ -0,0 +1,23 @@ +#!/usr/bin/python +ten_things = "Apples oranges crows telephone light sugar" +print "wait there's not 10 things in that list, let's fix that." + +stuff = ten_things.split(' ') +more_stuff = ["day", "night", "song", "friends", "corn", "banana", "girl", "boy"] + +while len(stuff) != 10: + next_one = more_stuff.pop() + print "adding: ", next_one + stuff.append(next_one) + print "there's %d items now." % len(stuff) + +print "there we go:", stuff + +print "let's do some things with stuff." + +print stuff[1] +print stuff[-1] +print stuff.pop() +print ' '.join(stuff) +print '#'.join(stuff[3:5]) + diff --git a/ex40.py b/ex40.py new file mode 100644 index 00000000000..577334259e4 --- /dev/null +++ b/ex40.py @@ -0,0 +1,21 @@ +#!/usr/bin/python +cities = {'CA': 'San francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} +cities['NY']= 'New york' +cities['OR']= 'Portland' + +def find_city(themap, state): + if state in themap: + return themap[state] + else: + return "Not found." + +cities['_find'] = find_city + +while True: + print "state? (ENTER to quit)", + state = raw_input("> ") + if not state: break + + city_found = cities['_find'](cities, state) + print city_found + diff --git a/ex41.py b/ex41.py new file mode 100644 index 00000000000..97615422c56 --- /dev/null +++ b/ex41.py @@ -0,0 +1,158 @@ +#!/usr/bin/python +from sys import exit +from random import randint + +def death(): + quips = ["you died. you kinda suck at this.", + "Nice job, you died ...jackass.", + "such a luser.", + "I have a small puppy that's better at this."] + print quips[randint(0,len(quips)-1)] + exit(1) + +def central_corridor(): + print "the gothons of planet percal #25 have invaded your ship and destroyed" + print "your entire crew, you are the last surviving member and your last" + print "mission is to get neutron destruct bomb from the weapons armory," + print "put it in the bridge, and blow the ship up after getting into an" + print "escape pod." + print "\n" + print "you're running down the central corridor to the weapons armory when" + print "a gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" + print "flowing around his hate filled body. he's blocking the door to the" + print "armory and about to pull a weapon to blast you." + + action = raw_input("> ") + + if action == "shoot!": + print "quick on the draw you yank out your blaster and fire it at the gothon." + print "his clown costume is flowing and moving around his body, which throws" + print "off your aim, your laser hits his costume but misses him entirely. this" + print "completely ruins his brand new costume his mother bought him, which" + print "makes him sly into an insane rage and blast you repeatedly in the face until" + print "you are dead. then he eates you." + return 'death' + + elif action == "dodge!": + print "like a world class boxer you dodge, weave, slip and slide right" + print "as the gothon's blaster cranks a laser past your head." + print "in the middle of your artful dodge your foot slips and you" + print "bang your head on the metal wall and pass out." + print "you wake up shortly after only to die as the gothon stomps on" + print "your head and eats you." + return 'death' + + elif action == "tell a joke": + print "lucky for you they made you learn gothon insults in the academy." + print "you tell the one gothon joke you know:" + print "lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr." + print "the gothon stops, tries not to laugh, then busts out laughing and can't move." + print "While he's laughing you run up and shoot him square in the head" + print "putting him down, then jump through the weapon armory door." + return 'laser_weapon_armory' + else: + print "DOES NOT COMPUTE!" + return 'central_corridor' + +def laser_weapon_armory(): + print "you do a dive roll into the weapon armory, crouch and scan the room" + print "for more gothons that might be hiding. it's dead quiet, too quiet." + print "you stand up and run to the far side of the room and find the" + print "neutron bomb in its container. there's a keypad lock on the box" + print "and you need the code to get the bomb out. if you get the code" + print "wrong 10 times then the lock closes forever and you can't" + print "get the bomb. the code is 3 digits." + + code ="%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) + guess = raw_input("[keypad]> ") + guesses = 0 + while guess != code and guesses < 10: + print "bzzzzeddd!" + guesses += 1 + guess = raw_input("[keypad]> ") + + if guess == code: + print "the container clicks open and the seal breaks, letting gas out." + print "you grab the nuetron bomb and run as fast as you can to the" + print "bridge where you must place it in the right spot." + return 'the_bridge' + + else: + print "the lock buzzes" + print "melting sound" + print "you decide to sit there" + print "ship from their ship and you die." + return 'death' + +def the_bridge(): + print "you burst onto the bridge" + print "under your arm" + print "take control of the ship" + print "clown costume than the last" + print "weapons out yet" + print "arm and don't want to set it off." + + action = raw_input("> ") + if action == "throw the bomb": + print "throw the bomb at the group of gothons" + print "and make a leap for the door." + print "gothon shoots you" + print "as you die you see another gothon" + print "the bomb" + print "it goes off" + return 'death' + elif action =="slowly place the bomb": + print "you point your blaster at the bomb" + print "and the gothons put their hands up and start to sweat" + print "you inch" + print "place the bomb on the floor" + print "you jump back" + print "and blast the lock" + print "now that the bomb is placed" + print "get off" + return 'escape_pod' + else: + print "does not compute!" + return "the bridge" +def escape_pod(): + print "rush" + print "escape" + print "clear of" + print "interference" + print "pick one to take" + print "have no time to look" + print "do you take?" + + good_pod = randint(1,5) + guess = raw_input("[pod #]> ") + if int(guess) != good_pod: + print "jump into pod %s" % guess + print "the pod escape" + print "implodes" + print "into jam jelly." + return 'death' + else: + print "jump into pod %s" % guess + print "slides" + print "planet below" + print "back and see" + print "bright star" + print "time. you won!" + exit(0) +ROOMS = { + 'death': death, + 'central_corridor': central_corridor, + 'laser_weapon_armory': laser_weapon_armory, + 'the_bridge': the_bridge, + 'escape_pod': escape_pod +} + + +def runner(map, start): + next = start + + while True: + room = map[next] + print "\n-----------" + next = room() +runner(ROOMS, 'central_corridor') diff --git a/ex42.py b/ex42.py new file mode 100644 index 00000000000..bbc3b11b928 --- /dev/null +++ b/ex42.py @@ -0,0 +1,33 @@ +#!/usr/bin/python + +class TheThing(object): + + def __init__(self): + self.number = 0 + def some_function(self): + print "I got called." + def add_me_up(self, more): + self.number += more + return self.number + +a = TheThing(); +b = TheThing() + +a.some_function() +b.some_function() + +print a.add_me_up(20) +print a.add_me_up(20) +print b.add_me_up(30) +print b.add_me_up(30) + +print a.number +print b.number + +class TheMultiplier(object): + def __init__(self, base): + self.base = base + def do_it(self,m): + return m * self.base +x = TheMultiplier(a.number) +print x.do_it(b.number) diff --git a/raw_input.py b/raw_input.py new file mode 100644 index 00000000000..a41fa84f818 --- /dev/null +++ b/raw_input.py @@ -0,0 +1,5 @@ +#!/usr/bin/python +age = raw_input("How old are you?") +height = raw_input("How tall are you?") +weight = raw_input("How much do you weigh?") +print "so, you're %r old,%r tall and %r heavy." %(age, height,weight) diff --git a/raw_input.pyc b/raw_input.pyc new file mode 100644 index 00000000000..733df8ec5b5 Binary files /dev/null and b/raw_input.pyc differ diff --git a/try.py b/try.py new file mode 100644 index 00000000000..d51a607fb48 --- /dev/null +++ b/try.py @@ -0,0 +1,11 @@ +#!/usr/bin/python + +import sys +try: + s = raw_input('Enter something----->') +except EOFError: + print "\nwhy did you do an EOF on me?" + sys.exit() +except: + print "\nsome error/exception occured." +print "done"