Friday, September 30, 2011

LPTHW Exercise 44

In this exercise we take the code written in exercise 43 and comment it.

There is still plenty of scope for improvement, such as proper super class and subclass relationships between individual rooms and a proposed Room superclass.

Here's the code.

# LPTHW Exercise 43
import random
""" This module contains classes which denote the Game and individual rooms of the game."""
class Game(object):
"""
This class represents the Game. It is what you would expect in a game
engine.
This game consists of rooms. You can do different things in each room.
The Game class holds references to various room objects and also
provides a base set of game commands to query the current room, navigate
among rooms, etc. Each room is expected to have it's own set of commands
and a help command which will list all other commands.
"""
def __init__(self):
# Add commands and their help text to a dict
self.cmds = {}
self.cmds["rooms"] = "Prints the list of available rooms"
self.cmds["room"] = "Print the name of the current room. If followed by an argument then user will be taken to that room"
self.cmds["help"] = "Lists all the commands"
self.cmds["quit"] = "Quit the game"
# set room names along with their object instances in a dict
self._rooms = {}
self._rooms['SpacedRepitition'] = SpacedRepitition(self)
# set the current room
self.current_room = None
#A placeholder list of commands representing that no command has been issued
self._nocmd = ["nocmd"]
def start(self):
"""
Starts the game and provides an input prompt to the user to enter commands
"""
print "Welcome to this wonderful game of self development!"
print "Please enter your command at the prompt below. Type 'help' to get assistance."
#The main loop of the game
while(True):
cmd = raw_input("> ")
args = cmd.split(' ')
while args != None and len(args) > 0 and args[0] in self.cmds:
cmd_func = getattr(self, args[0])
# A command could return a list of arguments which may signify
# the next command to execute
args = cmd_func(args)
if args == None:
print "You did not enter a command"
elif len(args) == 0:
#Control will usually come here because it came out of the inner while loop
print "You did not enter a command"
elif args == self._nocmd:
pass
else:
print "Unknown command '" + args[0] + "'"
def help(self, args):
"""
A function for the 'help' command
"""
for cmd in self.cmds:
print cmd + " - " + self.cmds[cmd]
return self._nocmd
def rooms(self, args):
"""
A function for the 'rooms' command
"""
print "Rooms available in this game are:"
count = 0
for room in self._rooms:
count += 1
print "%d. %s" % (count, room)
return self._nocmd
def room(self, args):
"""
A function for the 'room' command
"""
if(len(args) > 1):
# User seems to be indicating that they want to enter a room
room_name = args[1]
if room_name in self._rooms:
room_obj = self._rooms[room_name]
self.current_room = room_name
args = room_obj.enter()
return args
else:
print "Sorry, we could not find a room by that name '%s'" % room_name
else:
# User wants to know which room they are in
#we need to provide hallway as a default room
if self.current_room == None:
print "You are in the hallway, and have not yet entered a room."
else:
print "You are in '%s'" % self.current_room
return self._nocmd
def quit(self, args):
"""
A function for the 'quit' command
"""
print "Thank you for playing with us, have a wonderful day !"
exit(0)
def has_cmd(self, the_cmd):
"""
Determines if this class supports the specified command.
Returns True if it does and False otherwise
"""
if(the_cmd in self.cmds):
return True
else:
return False
class SpacedRepitition(object):
"""
Class to represent the SpacedRepitition room
"""
def __init__(self, _game):
"""
Requires an object of type Game. This represents the game within which this room is operating.
"""
self.game = _game
# Add commands available in this room along with their help text
self.cmds = {}
self.cmds["help"] = "Lists all the commands"
self.cmds["topic"] = "Prints the current topic. If followed by an argument then the user will be switched to that topic"
self.cmds["topics"] = "Prints the list of available topics"
self.cmds["question"] = "Request to ask a question"
# Import all the files in which we have questions for various topics
import java_questions
import version_control_questions
import javascript_questions
import linux_questions
import mysql_questions
import misc_questions
import php_questions
import vim_questions
from question import Question
#Adds topics to this room. Right now the questions for each topic come
#from a separate python file.
self._topics = {
"version_control":version_control_questions.version_control_questions,
"java":java_questions.java_questions,
"javascript":javascript_questions.javascript_questions,
"linux":linux_questions.linux_questions,
"mysql":mysql_questions.mysql_questions,
"misc":misc_questions.misc_questions,
"php":php_questions.php_questions,
"vim":vim_questions.vim_questions
}
# Set the current topic
self._current_topic = None
def enter(self):
"""
Signifies that a user has entered this room. All the commands of this
room will now be available to the user
"""
# TODO: The room name should come from a static property which should also be accessed from the Game class
print "Welcome to the '%s' room" % "SpacedRepitition"
while(True):
# The main loop of this room
cmd = raw_input("SpacedRepitition > ")
args = cmd.split(' ')
if(args[0] in self.cmds):
# We first see if the command is available in this room. If it is
# then we will invoke the function which represents the command
cmd_func = getattr(self, args[0])
cmd_func(args)
elif(self.game.has_cmd(args[0])):
# Next we check if it is available in the game. If it is then
# we will return the arguments to the game, so it may invoke
# the command as it sees fit
return args
else:
print "Unknown command '" + args[0] + "'"
def topics(self, args):
"""
A function for the 'topics' command
"""
print "The following topics are available"
count = 0
for topic in self._topics:
count += 1
print "%d. %s" % (count, topic)
def topic(self, args):
"""
A function for the 'topic' command
"""
if(len(args) > 1):
topic_name = args[1]
if topic_name in self._topics:
self._current_topic = topic_name
print "You will now be asked questions from the following topic %s." % self._current_topic
print "Please use the 'question' command to request a question."
else:
print "Sorry, we could not find a topic by that name '%s'" % topic_name
else:
#we need to provide hallway as a default room
if self._current_topic == None:
print "You have not selected any topic."
else:
print "You will be asked questions from the following topic '%s'" % self._current_topic
def question(self, args):
"""
A function for the 'question' command
"""
if self._current_topic != None:
current_topic = self._topics[self._current_topic]
question_index = random.randint(0, len(self._topics[self._current_topic])-1)
the_question = current_topic[question_index]
print the_question._question + "\n"
answer = raw_input("Please type your answer >")
print "\nThe correct answer is printed on the line below. Please compare it with what you typed....."
print the_question._answer
print "\n\n"
else:
print "Please select a topic first."
def help(self, args):
"""
A function for the 'help' command
"""
print "Commands available from all rooms"
self.game.help(args)
print "\nCommands available in this room"
for cmd in self.cmds:
print "%s - %s" % (cmd, self.cmds[cmd])
#=================== main ============================
if(__name__ == "__main__"):
game = Game()
game.start()
view raw ex43_game.py hosted with ❤ by GitHub
class Question(object):
"""
This class represents a Question
"""
def __init__(self, question, answer):
"""
Accepts string objects for question and answer. They Will be set them in this question object.
They can be accessed using the _question and _answer properties of the Question class.
Both the 'question' and 'answer' arguments must of of type 'str'. If they are of any other type
an exception will be raised
"""
#Validate input arguments
str_type = type("")
if(type(question) != str_type):
msg = "Incorrect argument for 'question' - It is of type %r but it must be of type %r " % (type(question), str_type)
raise(BaseException(msg))
if(type(answer) != str_type):
msg = "Incorrect argument for 'answer' - It is of type %r but it must be of type %r " % (type(answer), str_type)
raise(BaseException(msg))
self._question = question
self._answer = answer
if __name__ == "__main__":
""" Test code for this module """
q1 = Question("q1", "a1")
try:
q2 = Question("q2", 2)
print "fail: Should have thrown an Exception"
except:
pass
try:
q3 = Question(3, "q3")
print "fail: Should have thrown an Exception"
except:
pass
view raw question.py hosted with ❤ by GitHub

LPTHW Exercise 43

In this exercise I have made a game. The program is not perfect, but it works well. I still need to refactor it for the following:

1. Use proper class..subclass relationships. For example SpacedRepitition should be a subclass of another class called Room

2. Add proper documentation

3. Use proper coding standards

I will address most of these issues in the next exercise

# LPTHW Exercise 43
import random
""" This module contains classes which denote the Game and individual rooms of the game."""
class Game(object):
def __init__(self):
self.cmds = {}
self.cmds["rooms"] = "Prints the list of available rooms"
self.cmds["room"] = "Print the name of the current room. If followed by an argument then user will be taken to that room"
self.cmds["help"] = "Lists all the commands"
self.cmds["quit"] = "Quit the game"
self._rooms = {}
self._rooms['SpacedRepitition'] = SpacedRepitition(self)
self.current_room = None
self._nocmd = ["nocmd"]
def start(self):
print "Welcome to this wonderful game of self development!"
print "Please enter your command at the prompt below. Type 'help' to get assistance."
while(True):
cmd = raw_input("> ")
args = cmd.split(' ')
while args != None and len(args) > 0 and args[0] in self.cmds:
cmd_func = getattr(self, args[0])
args = cmd_func(args)
if args == None:
print "You did not enter a command"
elif len(args) == 0:
print "You did not enter a command"
elif args == self._nocmd:
pass
else:
print "Unknown command '" + args[0] + "'"
def help(self, args):
for cmd in self.cmds:
print cmd + " - " + self.cmds[cmd]
return self._nocmd
def rooms(self, args):
print "Rooms available in this game are:"
count = 0
for room in self._rooms:
count += 1
print "%d. %s" % (count, room)
return self._nocmd
def room(self, args):
if(len(args) > 1):
room_name = args[1]
if room_name in self._rooms:
room_obj = self._rooms[room_name]
self.current_room = room_name
args = room_obj.enter()
return args
else:
print "Sorry, we could not find a room by that name '%s'" % room_name
else:
#we need to provide hallway as a default room
if self.current_room == None:
print "You are in the hallway, and have not yet entered a room."
else:
print "You are in '%s'" % self.current_room
return self._nocmd
def quit(self, args):
print "Thank you for playing with us, have a wonderful day !"
exit(0)
def has_cmd(self, the_cmd):
if(the_cmd in self.cmds):
return True
else:
return False
# -----------------------------------------------------------------------------
class SpacedRepitition(object):
def __init__(self, _game):
self.game = _game
# Add commands available in this room
self.cmds = {}
self.cmds["help"] = "Lists all the commands"
self.cmds["topic"] = "Prints the current topic. If followed by an argument then the user will be switched to that topic"
self.cmds["topics"] = "Prints the list of available topics"
self.cmds["question"] = "Request to ask a question"
import java_questions
import version_control_questions
import javascript_questions
import linux_questions
import mysql_questions
import misc_questions
import php_questions
import vim_questions
from question import Question
self._topics = {
"version_control":version_control_questions.version_control_questions,
"java":java_questions.java_questions,
"javascript":javascript_questions.javascript_questions,
"linux":linux_questions.linux_questions,
"mysql":mysql_questions.mysql_questions,
"misc":misc_questions.misc_questions,
"php":php_questions.php_questions,
"vim":vim_questions.vim_questions
}
self._current_topic = None
def enter(self):
# TODO: The room name should come from a static property which should also be accessed from the Game class
print "Welcome to the '%s' room" % "SpacedRepitition"
while(True):
cmd = raw_input("SpacedRepitition > ")
args = cmd.split(' ')
if(args[0] in self.cmds):
cmd_func = getattr(self, args[0])
cmd_func(args)
elif(self.game.has_cmd(args[0])):
return args
else:
print "Unknown command '" + args[0] + "'"
def topics(self, args):
print "The following topics are available"
count = 0
for topic in self._topics:
count += 1
print "%d. %s" % (count, topic)
def topic(self, args):
if(len(args) > 1):
topic_name = args[1]
if topic_name in self._topics:
self._current_topic = topic_name
print "You will now be asked questions from the following topic %s." % self._current_topic
print "Please use the 'question' command to request a question."
else:
print "Sorry, we could not find a topic by that name '%s'" % topic_name
else:
#we need to provide hallway as a default room
if self._current_topic == None:
print "You have not selected any topic."
else:
print "You will be asked questions from the following topic '%s'" % self._current_topic
def question(self, args):
if self._current_topic != None:
current_topic = self._topics[self._current_topic]
question_index = random.randint(0, len(self._topics[self._current_topic])-1)
the_question = current_topic[question_index]
print the_question._question + "\n"
answer = raw_input("Please type your answer >")
print "\nThe correct answer is printed on the line below. Please compare it with what you typed....."
print the_question._answer
print "\n\n"
else:
print "Please select a topic first."
def help(self, args):
print "Commands available from all rooms"
self.game.help(args)
print "\nCommands available in this room"
for cmd in self.cmds:
print "%s - %s" % (cmd, self.cmds[cmd])
if(__name__ == "__main__"):
game = Game()
game.start()
view raw ex43_game.py hosted with ❤ by GitHub
class Question(object):
def __init__(self, question, answer):
self._question = question
self._answer = answer
view raw question.py hosted with ❤ by GitHub
from question import Question
# Add version control questions
version_control_questions = []
question = "In Git, how can I find out all the commits done on HEAD but not pushed to origin ?"
answer = "git log origin/master..HEAD"
version_control_questions.append(Question(question, answer))
question = "In Git, how can I find out what is available on origin/master for me to fetch ?"
answer = "git fetch origin/master"
version_control_questions.append(Question(question, answer))
question = "In Git, how can I view all the files which were part of a commit ?"
answer = "git log format=short --name-only \n See http://stackoverflow.com/questions/424071/how-do-i-list-all-the-files-for-a-commit-in-git"
version_control_questions.append(Question(question, answer))

Thursday, September 29, 2011

LPTHW Exercise 42

In this exercise we re-create the Gothons game with classes instead of "functions and maps"

The getattr function is used to obtain an attribute from an object using a String to identify the needed attribute. Ref [1]

# LPTHW Exercise 42
from sys import exit
from random import randint
class Game(object):
def __init__(self, start):
self.quips = [
"You died. You suck at this!",
"Your mom would be proud, if she were smarter.",
"Such a luser",
"I have a small puppy that is better at this."
]
self.start = start
def play(self):
next = self.start
while(True):
print "\n--------"
room = getattr(self, next)
next = room()
def death(self):
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
def central_corridor(self):
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 the 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 fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats 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(self):
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 neutron 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 one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
def the_bridge(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
def escape_pod(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)
a_game = Game("central_corridor")
a_game.play()
view raw ex42.py hosted with ❤ by GitHub

Wednesday, September 28, 2011

LPTHW Exercise 41

Gosh, I honestly could not type this in. Copy paste...

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 the 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 fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats 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 neutron 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 one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
def the_bridge():
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
def escape_pod():
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
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')
view raw ex41.py hosted with ❤ by GitHub

LPTHW Exercise 40

In this exercise we learn about Maps. They are also called 'dictionary' in Python. An interesting thing we do in this exercise is putting a function in the map.

# LPTHW Exercise 40
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"
# ok pay attention!
cities['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break
# this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
view raw ex40.py hosted with ❤ by GitHub

LPTHW Exercise 39

In this exercise we do some stuff with lists...




# LPTHW Exercise 39
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 = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "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] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!
view raw ex39.py hosted with ❤ by GitHub

Tuesday, September 27, 2011

LPTHW Exercise 37

Keywords

  • and - Logical AND operation
  • del- Deletes objects. These objects could be local variables, or even elements from a list. - References [1] [2]
  • from - Used for importing elements from modules
  • not - The logical NOT operation
  • while - Used for looping until the condition in while remains true
  • as - When used with the 'import' statement, the as keyword is used to rename the bound object. It can also be used with the 'with' statement... though I am not sure what that statement does.
  • elif - 'else if'
  • global - This causes a local variable to be visible outside of it's scope. Ref [1]
  • or - The logical OR operation
  • with - This seems like a more convenient alternative to try...finally when there is a setup, execution, and teardown cycle to be performed. Ref [1]
  • assert - The 'assert' statement is used to put error checking in your code. It seems to be very similar to what 'assert' does in Java
  • else - 'else' part of a conditional
  • if - Conditional
  • pass - The 'pass' statement does nothing. It is used when a statement is required syntactically, but nothing needs to be done. Ref [1]
  • yield - The yield statement causes a function to return a generator. When this generator is run, it will return a value specified by the yield statement and will do so every time it is run until the function runs out of values. This is also akin to continuations. Ref [1]. Do generators always return iterables ?
  • break - The 'break' statement breaks out of the immediately enclosing 'for' or 'while' loop. Ref [1]
  • except - The 'except' keyword is used as a counterpart to the 'try' keyword. It has a similar function to the 'catch' keyword in Java. Ref [1]
  • import - Used for importing modules and their elements
  • print - Used for printing something to the console
  • class - Used for defining a class
  • exec - Supports dynamic execution of Python code
  • in - The inclusion operator
  • raise - Raising an exception
  • continue - Continue back to the start of the loop
  • finally - The cleanup block after a try...except statement. Ref [1]
  • is - Used to determine if two values are stored in the same memory location. Ref [1]
  • return - Used to return a value from a function
  • def - Keyword used to define a function
  • for - The for loop
  • lambda - Used to create small anonymous functions. Ref [1]
  • try - Used to enclose code which could throw Exceptions. It must be followed by an 'except' statement.
Notes:
This webpage says that the 'del' keyword deletes objects. What exactly does that mean? Does it delete objects from lists, sequences, etc, or does it also delete objects from within other objects, or entire objects ?

Data Types

For data types, write out what makes up each one. For example, with strings write out how you create a string. For numbers write out a few numbers.

  • True - The boolean true value
  • False - The boolean false value
  • None - Represents nothing... looks like it is similar to the 'null' keyword in Java
  • strings - The string datatype which is a sequence of characters
  • numbers - Python supports several numeric data types
  • floats - Represents floating point numbers as per the IEEE 854-1987 standard
  • lists - An ordered collection of items

String Escapes Sequences

For string escape sequences, use them in strings to make sure they do what you think they do.

  • \\ - Result is a single backslash
  • \' - Result is the ' character
  • \" - Result is the " character
  • \a - Result is the ASCII bell
  • \b - ACSII backspace
  • \f - ASCII formfeed
  • \n - ASCII linefeed
  • \r - ASCII carriage return
  • \t - ASCII horizontal tab
  • \v - ASCII vertical tab

String Formats

Same thing for string formats: use them in some strings to know what they do.

  • %d - signed decimal
  • %i - signed integer decimal
  • %o - signed octal value
  • %u - Obsolete type now... identical to %d
  • %x - Signed hexadecimal lowercase
  • %X - Signed hexadecimal uppercase
  • %e - Floating point exponential format (lowercase)
  • %E - Floating point exponential format (uppercase)
  • %f - Floating point decimal format
  • %F - Floating point decimal format
  • %g - Floating point format. Uses lowercase format if exponent is less than -4 or not less than precision. Decimal otherwise
  • %G - Floating point format. Uses uppercase format if exponent is less than -4 or not less than precision. Decimal otherwise
  • %c - Single character. Accepts integer or single character string
  • %r - Any Python object
  • %s - String
  • %% - Results in the % character... no argument is converted

Operators

Some of these may be unfamiliar to you, but look them up anyway. Find out what they do, and if you still can't figure it out, save it for later.

  • + - addition operator
  • - - subtraction operator
  • * - multiplication operator
  • ** - The power operator. a ** b will give a to the power b
  • / - The division operator
  • // - Floor division. 9 //2 is 4
  • % - Modulus operator
  • < - Less than
  • > - Greater than
  • <= - Less than equal to
  • >= - Greater than equal to
  • == - Equality
  • != - Not equal to
  • <> - Not equal to
  • ( ) - Parenthesis for defining proper precedence
  • [ ] - Used for defining lists
  • { } - Used for defining maps ?
  • @ - Decorator
  • , - Used to separate values in a tuple
  • : - Used to delimit the key and value in map entries
  • . - Used to identify a method on a referenced object or module
  • = - Assignment operator
  • ; - Combines multiple statements into one. See [1]
  • += - Add and assign (the ones below are similar... do something and assign)
  • -=
  • *=
  • /=
  • //=
  • %=
  • **=

LPTHW Exercise 36

In this exercise I created a simple text based game. This game consists of countries and capitals. A user is flown to a country, where the immigration officer asks them the name of the capital. If you answer correctly, you get a point, if you answer incorrectly you do not get any points. The game quits when the user has correctly guessed the capitals of all the countries, or if they type CTRL-C.

Stuff I learned:
  • How to generate a random number in Python
  • How to get the length of a list
  • We can nest lists within lists
  • A function can return multiple values
  • The main function has a really strange syntax
  • The ++ increment operator is not supported in Python
  • Making a simple game is fun


from sys import exit
import random
countries = [['India', 'New Delhi'], ['United States of America', 'New York'], ['Afghanistan', 'Kabul'], ['Australia', 'Canberra'], ['Austria', 'Vienna'], ['Cambodia', 'Phnom Penh']]
countries_answered = []
def get_random_country_and_capital():
randint = random.randint(0, countryCount-1)
country = countries[randint][0]
capital = countries[randint][1]
while(country in countries_answered):
randint = random.randint(0, countryCount-1)
country = countries[randint][0]
capital = countries[randint][1]
return country, capital
if __name__ == "__main__":
points = 0
print "Hello and welcome to the travel game"
countryCount = len(countries)
print "Our world has %r countries" % countryCount
start = raw_input("Are you ready to start the game ? (yes|no)")
if start == "no":
print "Goodbye !"
exit(0)
else:
# Start the game
name = raw_input("What is your name ? ")
print "Fasten your seat belt %s we are getting started ! If you want to quit midway, press CTRL-C" % name
while(True):
country, capital = get_random_country_and_capital()
print "You have landed in %s" % country
print "The immigration officer wants to find out if you know the capital of %s" % country
answer = raw_input("Please type the capital of %s : " % country)
if answer.lower() == capital.lower():
points += 1
countries_answered.append(country)
print "Awesome! That is absolutely right"
print "Your current score is %d" % points
if(points == countryCount):
print "You have earned the maximum points in this game. We hope you enjoyed playing it"
exit(0)
else:
print "Sorry that is the wrong answer!"
view raw ex36.py hosted with ❤ by GitHub


LPTHW Exercise 35

In this exercise we use branches in functions.

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 cthulu_room():
print "Here you see the great evil Cthulu."
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:
cthulu_room()
def dead(why):
print why, "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":
cthulu_room()
else:
dead("You stumble around the room until you starve.")
start()
view raw ex35.py hosted with ❤ by GitHub

LPTHW Exercise 34

In this exercise we learn how to get elements from a list.

animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']

print "The first animal is %s" % animals[0]

I did not create any Python files for this exercise. Did it in the console.

LPTHW Exercise 33

Completed exercise 33. In this exercise we learn about the while loop in Python.

# LPTHW Exercise 33
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
view raw ex33.py hosted with ❤ by GitHub

LPTHW Exercise 32

In this exercise we work with lists. A list is an ordered collection of items. We can iterate through all the items in a list, using a for..in loop. A range generates a list in an arithmetic progression. We can add elements to a list using the 'append' statement.

#LPTHW Exercise 32
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 does 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
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was: %d" % i
view raw ex32.py hosted with ❤ by GitHub

LPTHW Exercise 31

So far we used if..elif to print different things based on some values. But in real programs, we usually use conditions to make decisions based on user input. In this exercise, we take user input and make decisions based on it.

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 a 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 "You stare into the endless abyss at Cthuhlu'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 stumble around and fall on a knife and die. Good job!"
view raw ex31.py hosted with ❤ by GitHub

LPTHW Exercise 30

In this exercise, we learned how to use if...elif

#LPTHW Exercise 30
people = 30
cars = 40
buses = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
view raw ex30.py hosted with ❤ by GitHub

LPTHW Exercise 29

Completed exercise 29. This exercise covered the 'if' statement in Python.

Some learnings:
  1. The if statement does not need () after it
  2. Should end with ':'
  3. Since it is a block, it's contents should be indented
Here is the code.

# LPTHW Exercise 29
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."
view raw ex29.py hosted with ❤ by GitHub

LPTHW Exercise 28

In this exercise we work with boolean and equality operators in Python. Interestingly Python uses the words 'and' 'or' 'not' for boolean operators, instead of '&&' '||'. Python also uses the words 'True' and 'False' to denote the boolean types true, and false respectively.

I completed the exercise which was to evaluate some logic statements and correctly guess what the answer should be.

For extra credits I also checked out the equality operators in Python. Here's the list:

== Equal to
!= Not equal to
<> Not equal to
< Less than
> Greater than
<= Less than equal to
>= Greater than equal to

While looking at the page describing Python operators, I came across membership operators, which I found quite interested. Python has two membership operators which can work with sequences such as lists, tuples, and strings.

LPTHW Exercise 27

Exercise 27 is about logic and truth tables. Since I have been programming for a while, I am familiar with this, and am skipping the exercise.

LPTHW Exercise 26 - Test

This is a simple test, where we are given a file with broken code, and we have to fix it. I fixed the file and tested it. Not including it to avoid spoiling anyone's experience.

LPTHW Exercise 25

Exercise 25 is an "even more practice exercise"

In this exercise we practice writing and using functions.

Stuff I learned:
  • We can pop an element from a list, and when we do that the element is removed from the list
  • We can split a String based on a delimiter
  • We can use the sort function to sort a list



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_sentance(sentance):
"""Takes in a full sentance and returns the sorted words."""
words = break_words(sentance)
return sort_words(words)
def print_first_and_last(sentance):
"""Prints the first and last words of the sentance."""
words = break_words(sentance)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentance):
"""Sorts the words then prints the first and last one."""
words = sort_sentance(sentance)
print_first_word(words)
print_last_word(words)
view raw ex25.py hosted with ❤ by GitHub

Monday, September 26, 2011

Exercise 24 - More Practice

Completed exercise 24. This was a recap of some of the concepts covered till now. We recapped how to use different quotes in strings. We also learned how to format Strings using format character, we recapped how to define and use functions.




#LPTHW Exercise 24
print "Let's practice everything."
print 'You\'d need to know \'bout escapes 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 compressed 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 / 1000
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)
view raw ex24.py hosted with ❤ by GitHub

Friday, September 23, 2011

Exercise 23 - Read some code

For this exercise, we have to read some code and try to make sense of it. I have picked up 3 samples and will read each one of them.

  1. skills.py
  2. cookme_recipes.py
  3. Game of life
I read through the first two examples. The proved to be a very good starting point. They worked mostly with maps, creating them, getting keys, creating maps where the value is yet another map, etc.

The third one gameoflife.py is an implementation of Conways Game of Life in Python.

Completed reading it. This Python files used classed, functions, and a main function also. Nice experience, I will recommend that everyone try this exercise sincerely.


Exercise 22 - What do you know so far ?

In this exercise I am going to read through all the stuff I have done so far in the course, and then I will make a table of all the symbols, keywords, and concepts encountered in the course thus far.

# Used to comment a single like
+ Addition symbol
- Subtraction symbol
/ Division symbol
* Multiplication symbol
% Modulus symbol
< Less than symbol
> Greater than symbol
<= Less than equal to symbol
>= Greater than equal to symbol
= Assignment symbol
\ Escape character

* Can also precede an argument name given to a function. In this case it means that this variable will accept all the input given to the function as a list


def A keyword used to define functions
import Used to import a module or a symbol from a module

argv Is a symbol from the 'sys' module which contains all the command line arguments passed to a Python script, starting with the name of the script itself

print Prints the specified values to the standard console
raw_input Accepts raw input from a user from the standard console
open(filename) Opens a file and returns a handle to it. By default this function will open the file in read mode, but we can specify a mode and open it for writing, etc
read() A function which can be called on a file handle to read the contents of a file
close() A function which can be called on a file handle to close the file and free up resources on the OS
truncate() A function which can be called on a file handle to remove existing contents of a file to either the current position of the file pointer, or if we provide a size argument then it will be truncated to that size
write() A function which can be called on a file pointer to write to the file
exists() A function which takes a file pointer and determines if that file exists
len() A function which takes data and tells us the size of that data. It accepts a sequence or a mapping


Stuff I learned:
  1. In Python we use the 'print' function to print to the console
  2. In Python function calls need not have () like in Java
  3. In Python we use the '#' character to comment a single line. The C style comment '//' does not work in Python
  4. We do not have to end a statement with a ';' or any delimiter in Python
  5. Python Strings can be delimited by double quotes as well as single quotes
  6. A double quoted string can contain single quotes
  7. It is not compulsory to have a main method in Python
  8. The print function can take multiple arguments separated by ','
  9. When we give multiple values to the print function, it automatically puts a space in between them
  10. Since Python is dynamically typed, we do not need to specify the type of variables, nor do we need any special syntax like 'var' to define variable names
  11. When doing math operations in Python, if all the operands are integers, then the result will also be an Integer. If the operation is a division operation, then the result will be truncated to yield an Integer. However, if even one of the operands is a float, then all operands will be promoted to floating point numbers and the result will also be a float
  12. Python supports formatting of Strings with the % character
  13. There are many formatting characters in Python. %r is one of them. It will print the String representation of any object, by calling the repr() method of that object
  14. When we use %r for formatting, it surrounds the String between ''
  15. We can multiply a String with a number, such as "." * 10 - This will concatenate the String 10 times
  16. Strings can also be concatenated with the + operator
  17. We can specify triple quoted Strings. These can span multiple lines, and can also contain single and double quotes
  18. When we print something with the print statement, it automatically appends a newline character to the String when it is printed. We can override this functionality by ending the print with a ','
  19. raw_input("prompt") can also be given a String which will be used as a prompt
  20. In Python we can unpack a list into multiple variables by assigning a list to multiple variables (see ex13.py)
  21. If we type CTRL-C on the console when the program is expecting input, it results in a KeyboardInterrupt and the program will exit
  22. In Python functions do not have to be delimited with {}. Rather there contents are indented, and the function ends when the indentation comes back to the level before the function


LPTHW - Exercise 21

In this exercise we learn how to return values from functions.




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 for extra credit, type it in anyway.
print "Here's a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
view raw ex21.py hosted with ❤ by GitHub

Wednesday, September 14, 2011

LPTHW - Exercise 20

In this exercise, we combine functions and files. We create some functions to operate on files.

New things I learned:
1. We can use the seek() function on a file handle to take the file cursor to a particular position in the file
2. We can give multiple strings to the print function by separating them by a ','

# LPTHW - Exercise 20
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 "Let's first 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)
view raw ex20.py hosted with ❤ by GitHub

LPTHW - Exercise 19

In this exercise, we reinforce the things we learned in the previous exercise on functions. We also learn that variables inside a function are not connected to the variables outside the functions (scope).

#LPTHW - Exercise 19
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 scripts:"
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 "And we can combine the two, variables and math"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
view raw ex19.py hosted with ❤ by GitHub

LPTHW - Exercise 18

In this exercise, we learn how to define functions. Functions can be thought of as creating custom commands.

We use the 'def' keyword to create functions. The function's body needs to be indented with the same number of spaces in every line.

We can accept a parameter called *args (args can be replaced with anything else). This I believe takes a list of parameters which can be unpacked into multiple arguments as seen in the function 'print_two'

# LPTHW - Exercise 18
# this one islike your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no arguments
def print_none():
print "I got nothin'."
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
view raw ex18.py hosted with ❤ by GitHub

LPTHW - Exercise 17

In this exercise we will copy the contents of one file to another. In a past exercise, we learned how to read the contents of a file, and in another past exercise we learned how to write to a file. In this exercise, we will read the contents of one file and write it to another file.

The new things I learned in this exercise are:
1. We can use the exists() function to find out if a file exists
2. We can use the len() function to determine the size of data in a file=

# LPTHW - Exercise 17
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)
# we could do these two on one line too, how?
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 RETUEN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
#output.close()
input.close()
view raw gistfile1.txt hosted with ❤ by GitHub

Tuesday, September 13, 2011

LPTHW - Exercise 16

In the previous exercise we read the contents of a file. In this exercise we are going to read and write files.

We will open a file in the 'w' mode and then truncate it. Then we accept three lines of input from the user, and append them to the file.

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 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 we finally, close it."
target.close()
view raw ex16.py hosted with ❤ by GitHub


Extra Credit:

In the next example, we comment most of the lines of the solution and also reuse the prompt by using replacement characters.

# LPTHW Exercise 16
# Import the argv variable from the sys module
from sys import argv
#unpack the contents of argv into script and filename
script, filename = argv
#create a general variable which we will re-use for the prompt
prompt = "line %d: "
# Tell the user that we are going to erase the filename they mentioned in the cmd argument
print "We're going to erase %r." % filename
# Prompt the user that they can hit CTEL-C if they do not want to erase the file
print "If you don't want that, hit CTRL-C (^C)."
#Prompt the user that they can hit RETURN if they DO want to erase the file
print "If you want that hit RETURN."
# Take input from the user... this will determine if we will erase the file or not
raw_input("?")
print "Opening the file..."
#open the specified file and hold the fp in a variable called target
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
#truncate the file
target.truncate()
print "Now I'm going to ask you for three lines."
#aAccept three lined from the user
line1 = raw_input(prompt % 1)
line2 = raw_input(prompt % 2)
line3 = raw_input(prompt % 3)
print "I'm going to write these to the file."
#Write all the three lines to the file seperated with a newline
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And we finally, close it."
# Close the file
target.close()


We need not have called truncate on the fp, since opening a file in 'w' mode automatically truncates it.

Monday, September 12, 2011

LPTHW - Exercise 15

In this exercise, we will read the contents of a file and print them to the console.

from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ");
txt_again = open(file_again)
print txt_again.read()
view raw ex15.py hosted with ❤ by GitHub


Notes:

We use the open(filename) function to get a file handle, and then we use the read() function of the file handle object to read the contents of the file as a string.

I am sure there is a different way to read a binary file, and I am also sure there should be a way to buffer the input in case the file is very large, but read is the simplest way to get the job done. This is much better than Java where we have to jump through tons of hoops to read a file.

LPTHW - Exercise 14

In this exercise we use a value from the command line input to prompt the user.

#LPTHW Exercise 14
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
view raw ex14.py hosted with ❤ by GitHub


Questions:

1. The unpacking thing seems to basically work with lists on the RHS and a bunch of variables on the LHS. Not sure if that is right. Will have to find out.

LPTHW - Exercise 13

In this exercise we will learn how to accept command line arguments.

#LPTHW - Exercise 13
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
view raw ex13.py hosted with ❤ by GitHub


In the script above in the first line we import the 'argv' variable from the 'sys' module. This variable will hold the name of the script and all command line arguments given to it.

We unpack these values and assign them to the variables on the LHS.

Questions:
1. Does importing argv make is available, or does it also turn on the function of accepting command line arguments?

2. Here we assign the values to the variables on the LHS. However, we need to be sure that the command line parameters and the number of variables are the same. This is not always possible, especially when we do not know how many values the user will enter. Perhaps, this issue will be dealt with in a later exercise. I will leave it as is for now, but will try to answer it if it is not dealt with in a later exercise.

LPTHW - Exercise 12

In this exercise, we will provide some text to the raw_input() function as a parameter. This text will be used as the prompt. This is much easier than the previous exercise, where we first printed something (as a prompt) and then asked for input using the raw_input() function.

#LPTHW Exercise 12
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)
view raw ex12.py hosted with ❤ by GitHub


Extra Credits:

We can read the documentation of any function using the pydoc command. To quit the documentation, press 'q' on the command prompt.

LPTHW - Exercise 11

In this exercise we are going to accept input from the user.

#LPTHW Exercise 11
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
view raw ex11.py hosted with ❤ by GitHub


Notes and extra credits:

When we print something with the print statement, it normally ends with a newline. We can prevent the new line by ending the print statement with a ',' as shown in the example above.

The raw_input() function is used to read input from the console. It will read one line of input, and pass it to the program with the ending newline stripped out.

It seems we can load the 'readline' module to provide some elaborate editing and history features.

In the output of the above program, all the instances of %r are replaced by the output of running __repr() on the arguments. The output is always delimited with ''. Since the height also uses a ' within it, it must be escaped.

LPTHW - Exercise 10

In this exercise, we look at some more printing and escape characters. The "\" is the escape character in Python (just like in many other programming languages).

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat ="""
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
view raw ex10.py hosted with ❤ by GitHub


Extra Credit:

Escape characters are used to change the meaning of the character following it. For example \t will print the 'tab' character instead of 't'. All escape sequences supported by Python are listed on this page from the Python docs.

I tried replacing the triple double quotes in the example above with triple single quotes. When I ran the example, it ran just like the one with triple double quotes. I am not sure if there is any difference between them. Maybe if we use triple single quotes, then we can embed triple double quotes in them.

%s is better for printing because it is replaced by the String value, whereas %r is replaced by what is returned by the __repr function of the object (usually this is surrounded by double quotes).

#use ''' instead of """
print '''
This is a multi-line
string using \'''
instead of """
'''
# let's combine escape sequences and format strings
book = 'Learn Python The Hard Way'
print "We will now go to a new line \nand print this book's name - %s" % book
#Let us use %r instead of %s
print "We will now go to a new line \nand print this book's name - %r" % book

LPTHW - Exercise 9

In this exercise, we executed some more printing code. The new concept I learned in this exercise, is that we can use triple quotes to represent a string which can span multiple lines.

# Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something going on here.
With the three double-quotes.
We'l be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
view raw ex8.py hosted with ❤ by GitHub