[Tutor] Case acceptance using raw_input

2005-02-15 Thread Luke Jordan
Hi all, thanks to all for running such a great list.

Is there a better way for raw_input to accept both caps and lower case
letters than:

def aFunction():
   action = raw_input("Perform an action?(y,n): ")
   if action == 'y' or action == 'Y':
   anotherFunction()
   elif action == 'n' or action == 'N':
   yetAnotherFunction()
   else:
   aFunction()

Thanks!

--
No success or discovery is an accident. It is the result of time
invested in the process.


-- 
No success or discovery is an accident. It is the result of time
invested in the process.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Print text position problems when using triple quotes

2005-02-24 Thread Luke Jordan
Hi all,

I've tried a lot of experimenting and searching through various
tutorials, and I haven't been able to come up with a solution to this,
ostensibly simple, problem.

I'm writing a simple game (run in command line) in which narrative
text is printed in response to a user's decisions. The problem I'm
running into is that triple quotes used in an indented block preserves
the indentation when it prints. I'm writing code like this:

if userInput == 1:
some stuff
print """
texttexttexttexttexttexttexttext
"""
question within a question
if userInput == 1:
print """
texttexttexttexttexttexttexttext
texttexttexttexttexttexttexttext
"""
elif userInput == 2:
print """
owowowowowowowowowowow
"""

to preserve the text's position at left when I run it in the
command-line. The blocks get distorted and it becomes painful to read.

Is there a way to preserve the readability of the code and have
printed text from indented blocks, say, nested conditionals, appear
flush at left, not printed exactly where I've written them in the
script?

I know I can accomplish this using single quotes instead of triple
quotes, but I'm holding out hope that I can avoid putting each
sentence in a separate print statement.

if userInput == 1:
print "here's 80 characters"
print "now another 80"
etc.

Also, I've tried string.ljust(), but either I'm doing it wrong or it
isn't the trick I'm looking for.

Thanks for the help.

Luke
-- 
"If you think that was good, wait 'til you taste the antidote!"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print text position problems when using triple quotes

2005-02-24 Thread Luke Jordan
Execllent.

Many Thanks,

Luke



On Thu, 24 Feb 2005 13:15:41 -0500, Bill Mill <[EMAIL PROTECTED]> wrote:
> On Thu, 24 Feb 2005 13:14:13 -0500, Bill Mill <[EMAIL PROTECTED]> wrote:
> > On Thu, 24 Feb 2005 10:02:44 -0800, Luke Jordan <[EMAIL PROTECTED]> wrote:
> > > Hi all,
> > >
> > > I've tried a lot of experimenting and searching through various
> > > tutorials, and I haven't been able to come up with a solution to this,
> > > ostensibly simple, problem.
> > >
> > > I'm writing a simple game (run in command line) in which narrative
> > > text is printed in response to a user's decisions. The problem I'm
> > > running into is that triple quotes used in an indented block preserves
> > > the indentation when it prints. I'm writing code like this:
> > >
> > > if userInput == 1:
> > > some stuff
> > > print """
> > > texttexttexttexttexttexttexttext
> > > """
> > > question within a question
> > > if userInput == 1:
> > > print """
> > > texttexttexttexttexttexttexttext
> > > texttexttexttexttexttexttexttext
> > > """
> > > elif userInput == 2:
> > > print """
> > > owowowowowowowowowowow
> > > """
> > >
> > > to preserve the text's position at left when I run it in the
> > > command-line. The blocks get distorted and it becomes painful to read.
> > >
> > > Is there a way to preserve the readability of the code and have
> > > printed text from indented blocks, say, nested conditionals, appear
> > > flush at left, not printed exactly where I've written them in the
> > > script?
> >
> > Why not just take them out of the block, and either make them global
> > to the module or create a string module? i.e.:
> >
> > prompt1 = """This is a long string with %s string variables
> > %s scattered all over the place
> > as well as odd indentation %s
> > and funny lines
> >--
> >"""
> >
> > class foo:
> > def bar(self):
> 
> Sorry, I forgot that if it's in the module, you should declare prompt1
> as global by using "global prompt1" right here.
> 
> > print prompt1 % (var1, var2, var3)
> >
> > peace
> > Bill Mill
> > bill.mill at gmail.com
> >
> 


-- 
"If you think that was good, wait 'til you taste the antidote!"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Functions Calling Functions

2005-02-25 Thread Luke Jordan
Hi - 

I'm working on a command-line game. Is there anything wrong with
having each 'chapter' of the game be a function that links to other
chapters by calling them? I only ask because when a recent traceback
returned about 40 lines worth of error message, I realized that the
functions are all being run 'within each other' (ah-ha!).

Thanks!

-- 
"If you think that was good, wait 'til you taste the antidote!"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Associate functinos with Dictionary/Class Usage

2005-04-07 Thread Luke Jordan
Hi! 

My questions arose from reading the "Help with Classes" email that's
been on this list for the past couple of days.

I'm also writing a text game, but mine is puzzle not adventure.
Anyway, someone mentioned that you can key words to a dictionary to
have user input run functions.

I am looking for a little clarification of how exactly this would work.

1. How do I associate a function to a dict key?

2. If I do this, do objects have to be built from classes with
appropriate attributes?

Right now I am using a handful of methods that are called in if statements:

def takeItem(item):
items.append(item)
print "You took the", item

action = raw_input(">>> ")
if action == "take":
what = raw_input("What do you want to take? ")
takeItem(takeWhat)
elif action == "drink":
etc.

Thanks!

Luke

-- 
"Scalpelblood bucketpriestnext patient."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Associate functinos with Dictionary/Class Usage

2005-04-08 Thread Luke Jordan
Yes, Danny - that makes sense. I was getting hung up how to handle the
parens in this part

dict['some'](thing)

all clear now.

:-)

On Apr 7, 2005 4:40 PM, Danny Yoo <[EMAIL PROTECTED]> wrote:
> 
> 
> On Thu, 7 Apr 2005, Luke Jordan wrote:
> 
> > I am looking for a little clarification of how exactly this would work.
> >
> > 1. How do I associate a function to a dict key?
> 
> Hi Luke,
> 
> We're probably already familiar of values like numbers and strings, and
> how to give them names with variables:
> 
> ##
> >>> number = 42
> >>> name = "luke"
> >>> number
> 42
> >>> name
> 'luke'
> ##
> 
> 'number' is a name that refers to the value 42, and 'name' is a name (Doh!
> I must use a better variable name next time...) that refers to the value
> "luke".
> 
> And we also already know how to make functions and to call them:
> 
> ##
> >>> def square(x):
> ... return x * x
> ...
> >>> square(42)
> 1764
> ##
> 
> But what happens if we just say "square" at the interpreter?
> 
> ##
> >>> square
> 
> ##
> 
> The value of 'square' is a function value.
> 
> And just like any other value, we can assign it to another name:
> 
> ##
> >>> anotherNameForSquare = square
> >>> anotherNameForSquare(16)
> 256
> ##
> 
> And just like any other value, we can use it as a dictionary value:
> 
> ##
> >>> operators = {'^2': square}
> >>> operators['^2']
> 
> >>> operators['^2'](4)
> 16
> ##
> 
> Does this make sense so far?  Please feel free to ask more questions about
> this.  Best of wishes!
> 
> 


-- 
"Scalpelblood bucketpriestnext patient."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "Dispatching" functions with args

2005-04-13 Thread Luke Jordan
Hi!

I am using a suggestion from this list to handle calling different
functions conditionallly based on user input. What I'm trying to do is
have functions that are 'configurable' in the sense that a choice from
the user affects the way it performs.

This works:

def aFunc():
print "aFunc"

def dispatch(func):
while func is not None:
func = func()

But this does not:

def aFunc(configArg):
print "aFunc with argument"
print configArg

def anotherFunc(configArg):
print "anotherFunc with argument"
print configArg  
return aFunc,1

def dispatch(func,configArg):
while func is not None and configArg is not None:
func = func(configArg)

dispatch(anotherFunc,1)

I get TypeErrored:

Traceback (most recent call last):
  File "E:/gibberish/current work/test2.py", line 14, in ?
dispatch(aFunc,1)
  File "E:/gibberish/current work/test2.py", line 12, in dispatch
func = func(funcArg)
TypeError: 'tuple' object is not callable

I understand *that* a tuple is not callable, but not why this is
happening here, or how to solve this problem.

Thanks in advance for your input!

Luke

-- 
"Scalpelblood bucketpriestnext patient."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Filtering Spreadsheet Data

2005-05-23 Thread Luke Jordan
Hi All,

I have several frighteningly cumbersome reports to review at my new
job. I would like to write a python program to help me with my
analysis. The goal of the program is to filter out information that
doesn't meet certain requirements and print  relevant results back to
a legible report that I can do detailed research and analysis on. The
reports come to me in Excel format.

I have a solid understanding of basic programming.

Any guidance/advice/starting points would be greatly appreciated.

Thanks!

Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] database question

2007-06-29 Thread Luke Jordan

I've created a database as a shelve, where each value in the shelve file is
a record class instance that has attributes representing fields. Let's say I
enter 300 records in the shelve, then I decide to add a field to future
records, or remove a field from future records. How can I update the
existing records to include the new fields?

Thanks,

Luke


--
"If you think that was good, wait 'til you taste the antidote!"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] shelves behaving badly

2007-07-27 Thread Luke Jordan
i've implemented a database as a shelve of record class instances. some of
the fields in each record are dictionaries.

i needed to parse info from 3 different reports into the dictionary fields
in each record instance. i wrote the code to do this and tinkered it to fit
the different reports (i.e. information being in different columns, etc.).
for 2 of the reports, it runs fine. the required info turns up in the shelve
after i run the code, and i can exit and reenter python, open the shelve,
and it's all still there, where it should be. i've quadruple checked the
code for the third report, and it looks like it should work. in fact it
runs, and reports back that it did everything i told it to do; this includes
checking results as they occur at runtime. however, when i reopen the
shelve, none of that data is there. writeback is set to True, and I didn't
forget to close the shelve at the end of my code.

Now, if I open the shelve in the same shell as the script ran in, right
after I run it, I get the updated shelve. but any other method of opening
the shelve results in the shelve missing the data from the third report.

Any ideas what's going on here?

-- 
Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] shelves behaving badly

2007-08-02 Thread Luke Jordan
i think that some form of that is going on. actually there is only one
shelve; that's the confusing part, there are dictionaries in that shelve
though. i think it has to do with running things in IDLE and losing track of
what versions of shelves and modules are active in what shell, etc etc,
because i ran it again and it worked fine. it must be something to do with i
screwed something up in testing and forgot about it. i haven't found a
definitive answer to why it behaves this way, but so far the solution has
been to confine myself to one shell and to close out and reopen everytime
edits/reruns are made. thanks for the tip on checking things with os.

On 8/2/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> Luke Jordan wrote:
> > i've implemented a database as a shelve of record class instances. some
> > of the fields in each record are dictionaries.
> >
> > i needed to parse info from 3 different reports into the dictionary
> > fields in each record instance. i wrote the code to do this and tinkered
> > it to fit the different reports (i.e. information being in different
> > columns, etc.). for 2 of the reports, it runs fine. the required info
> > turns up in the shelve after i run the code, and i can exit and reenter
> > python, open the shelve, and it's all still there, where it should be.
> > i've quadruple checked the code for the third report, and it looks like
> > it should work. in fact it runs, and reports back that it did everything
> > i told it to do; this includes checking results as they occur at
> > runtime. however, when i reopen the shelve, none of that data is there.
> > writeback is set to True, and I didn't forget to close the shelve at the
> > end of my code.
> >
> > Now, if I open the shelve in the same shell as the script ran in, right
> > after I run it, I get the updated shelve. but any other method of
> > opening the shelve results in the shelve missing the data from the third
> > report.
> >
> > Any ideas what's going on here?
>
> It's pretty hard to say without seeing the code. I wonder if you are
> saving the third shelve in a different location than you think you are,
> and opening an old one in the other programs? Maybe check the full path
> of the file you save (use os.path.abspath()) and check the modified date
> of the one you open.
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sum of List Elements

2005-09-24 Thread Luke Jordan
Hi All,

I have spent an embarrassingly large amount of time trying to solve what on its face seems like a simple problem.

I have a list of intergers, and I want to assign the sum of the
intergers in the list to a variable. There are only intergers in the
list.

The best I have been able to do so far is to write a function that adds
list[0] and list[1], then list[1] and list [2], etc. Of course, this
isn't what I want.

I'd like to be able to sum a list of any size without having to type list[0]+list[1]

I am totally stumped.

:(

Luke
-- "Whether you're an honest man, or whether you're a thief,
depends on whose solicitor has given me my brief. " - Benjamin Franklin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sum of List Elements

2005-09-24 Thread Luke Jordan
Thanks for the help everyone, for answering a simple question and pointing me toward more resources.On 9/24/05, bob <
[EMAIL PROTECTED]> wrote:At 08:11 AM 9/24/2005, Luke Jordan wrote:>Hi All,
>>I have spent an embarrassingly large amount of time trying to solve what>on its face seems like a simple problem.>>I have a list of intergers, and I want to assign the sum of the intergers
>in the list to a variable. There are only intergers in the list.In addition to the other solutions there is the (more generic?) use of theoperator module and reduce function:import operator
reduce(operator.add, (1,2,3))Explore operator to see what other functions you can use.Also there are the array handling modules such as numarray.You can also define your own classes based on list and write methods to do
these operations.-- "Whether
you're an honest man, or whether you're a thief, depends on whose
solicitor has given me my brief. " - Benjamin Franklin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] dictionaries in classes

2005-10-14 Thread Luke Jordan
Hi,
 
Another stumped beginner here.
 
I'm trying to have functions to create, edit and store dictionaries within a class. What I can't figure out is how to retain the edits after making them. I think it has something to do with namespace. Ideally I'd like to pickle class instances and be able to access each instance's unique dictionaries through a 
classInst.dict arrangement. I don't know why I can't figure out how to make the dictionary an attribute of the class, or if that's even possible. Does the dict have to be a separate pickled file?
 
I've tried setting the dict in these namespaces:
 
class N:
    dict = {}
 
class N:
    def func(self):
    dict = {}
 
but neither of these is working for me. If I make the dict global, then all class instances could edit it, which is not what I'm shooting for either. I'm out of ideas, and I sense that there is something basic that I either don't know or am overlooking.

 
Thanks in advance.
 
Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Assign to vars by iteration

2005-10-17 Thread Luke Jordan
I've got a bunch of pickled class instances, and I'm trying to load them as variables using a function. The class has a self.name attribute, and I've got a list of 
self.name for all the instances pickled separately. When I would like to attach the names of each instance to the corresponding class instance (using self.name
 
def loadClassInst():
    classInstFile = "filepath"
    
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Please excuse the previous message sent in error

2005-10-17 Thread Luke Jordan
Sincerely, Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] define vars by iteration

2005-10-19 Thread Luke Jordan
I've got a bunch of pickled class instances with self.name attributes, and I would like to assign the instances themselves to variables named whatever is stored in 
self.name using a function. "Can't assign to literal", right? Is there a way to do this?
 
Thanks,
 
Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] define vars by iteration

2005-10-20 Thread Luke Jordan
Danny,
 
It does help. I'm still stuck on part of it though, maybe a little background will help.
 
To learn more about classes I decided to make a class Map, with many instances that have directions pointing to other Map instances. Each Map has different objects you can find on it, but is still a Map, so I have to customize each one. 

 
So if the only solution involves having names that could collide with builtins, I'd like to do it that way. I recognize the potential for chaos, but none of the names that I am using will collide (crossed fingers) becuase I'm using names like "Backyard", "Kitchen" etc. So, 

 
>>> MyBackyard = Map("MyBackyard")
>>> MyBackyard.setDirections()
set direction for N: MyHouse
set direction for S: TheStreet
>>> MyBackyard.N
MyHouse
 
etc, where MyHouse and TheStreet are made, via function, into MyHouse = Map("MyHouse") and so forth. Each instance is pickled in its own file named after self.name.
 

When I load the pickles like this
 
classNameList = ["Yard","Kitchen","LivingRoom"]
 
def getPickles():
    for name in classNameList:
    filepath = "C:\Python24\"+name+".dat"
    openedFile = file(filepath,"r")
    classInstanceName = pickle.load(openedFile)
    classInstanceName.name = classInstanceName
    print classInstanceName.name, classInstanceName
 
Yard 
Kitchen 
LivingRoom 
>>> LivingRoom

>>> Kitchen
name Kitchen not defined
>>> Yard
name Yard not defined
 
Also, I have done what I'm trying to do successfully by populating a dictionary with class instances named after self.name, which, after the function runs, I can access this way
 
>>> classDictionary["Yard"]

 
the thing is I would like to be able to get at Yard's attributes by typing
 
>>> Yard.anAttribute
garbage cans
 
at the prompt rather than
 
>>> Yard = classDictionary["Yard"]
>>> Yard.anAttribute
garbage cansIt's just that I can't pin down how to automate it, say through a loadAllMaps() func. 
Thanks again for your helpful advice!
 
Luke
 
On 10/19/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
On Wed, 19 Oct 2005, Luke Jordan wrote:> I've got a bunch of pickled class instances with
> self.name<http://self.name/>attributes, and I would like to assign the> instances themselves to variables> named whatever is stored in 
self.name <http://self.name/> using a function.> "Can't assign to literal", right? Is there a way to do this?Hi Luke,It's technically possible to do this, but discouraged.  The reason it's
not so safe is because some of those names might collide with your ownprogram's names, or with the builtins.  So if you start having pickledinstances with names like 'list' or 'open', havoc is bound to ensue.
Furthermore, Python variable names have some physical restrictions thatmay interfere with what you're trying to do:##>>> 4meUshouldnthave = 42File "", line 1
   4meUshouldnthave = 42  ^SyntaxError: invalid syntax##(For the gory details on what's allowed in a name "identifier", see:
http://www.python.org/doc/ref/identifiers.html)A safer way to do that I think you want is to use a separate dictionarycontainer for those instances.  As a concrete example:##class Person:
   def __init__(self, name):   self.name = namepeople_names = ['fred', 'barney', 'wilma', 'betty']people = {}for name in people_names:   people[name] = Person(name)
##Rather than using a direct variable name to refer to the person, we can goan indirect route, and refer to the corresponding entry in the 'people'dictionary.  Does this make sense?  This is safer because there's no
potential to munge up the toplevel, plus the 'name' keys won't have therestrictions that Python variable names have.Hope this helps!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] define vars by iteration

2005-10-24 Thread Luke Jordan
Thanks for this insight into classes. It often takes me a few days to absorb and respond because my job limits the time I can give to programming. But thanks again for taking the time to respond in a meaningful way.
 

I guess I could say that you changed my world when it comes to programming (sorry, low-hanging fruit :)) 
 
Luke 
On 10/20/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>  Also, I have done what I'm trying to do successfully by populating a> dictionary with class instances named after 
self.name ,> which, after the function runs, I can access this way>  >>> classDictionary["Yard"]> 
>  the thing is I would like to be able to get at Yard's attributes by typing>  >>> Yard.anAttribute> garbage cans>  at the prompt rather than>  >>> Yard = classDictionary["Yard"]
> >>> Yard.anAttribute> garbage cansHi Luke,One thing to note is that we can formally plunk and embed these places insome kind of World:##
class World:   def __init__(self):   self.places = {}   def attach(self, place):   """Given a place, attaches it to the world."""   self.places[
place.name] = place   def lookup(self, name):   return self.places[name]##If each place was aware that it was a part of a world --- that is, if we
embed the World inside each place as a part of a place's state --- thenthings might work out.For example, we might have a north-south corridor:##
class Corridor:   def __init__(self, world, name, northName, southName):   self.world, self.name, self.northName, self.southName = (   world, name, northName, southName)
   def N(self):   return self.world.lookup(self.northName)   def S(self):   return self.world.lookup(self.southName)##What's a little funny about this Corridor definition is that, because a
cooridor knows its in the world, it can also ask the world what place'northName' stands for in its N() method.Here's a small test:##>>> world = World()>>> world.attach
(Corridor(world, "Water cooler",...   north="Stairs", south="Boss Office"))>>> world.attach(Corridor(world, "Stairs",...   north="Wall", south="Water cooler"))
> world.lookup("Water cooler")<__main__.Corridor instance at 0x403a7fcc world.lookup("Water cooler").name'Water cooler'
>>> world.lookup("Water cooler").N()<__main__.Corridor instance at 0x403a7f6c world.lookup("Water cooler").N().name'Stairs'##Another advantage of having a central place is that saving and restoring
the environment is just a matter of pickling the world.  Hmmm... brinypickles... *grin* Sorry, I'm getting distracted by food.Does this make sense?  Please feel free to ask more questions.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor