Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Douglas Drumond
>
> But if you don't have l1 defined yet, you can't add to l2
> It's like:
> def a2():
> l1 = foo + l2
>
> UnboundLocalError: local variable 'foo' referenced before assignment
>
> It's because l1 (and foo at above example) is a local variable.
> a1's l1 is different from a2's l1.
>
>
> Sorry to be dense, but how, in what way, is a1's l1  different from a2's
> l1"?  Both are [1,2,3]*100 .
>
>
Both contain same value, but are in different namespaces (so, different
context and different memory areas).

If you do a="spam" and b="spam", this doesn't make them same variable, they
just have same value.

So is in that code. But to make it more confusing, names were the same.



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


[Tutor] addressbook program

2008-06-28 Thread Danny Laya
Hi I am making an addressBook program now, and you know some problem, the 
program doesn't work. This is the code :

# Loading the addressbook
filename = "addbook.dat"

def readBook(book)
    import os
    if os.path.exists(filename):
    store = open(filename,'r')
    for line in store:
        name = line.rstrip()
        entry = store.next().rstrip()
        book[name] = entry
    store.close()

# Saving the address book
def saveBook(book):
    store = open(filename,"w")
    for name,entry in book.items():
        store.write(name + '\n')
        store.write(entry + '\n')
    store.close()

# Getting User Input 
def getChoice(menu):
    print menu
    choice = int(raw_input("Select a choice(1-4): "))
    return choice

# Adding an entry
def addEntry(book):
    name = raw_input("Enter a name: ")
    entry = raw_input("Enter a street, town and phone number: ")
    book[name] = entry

# Removing an entry
def removeEntry(book):
    name = raw_input("Enter a name: ")
    del(book[name])

#Finding an Entry
def findEntry(book):
    name = raw_input("Enter a name: ")
    if name in book:
        print name, book[name]
    else: print "Sorry, no entry for: ", name

# Quitting the program
def main():
    theMenu = '''
    1) Add Entry
    2) Remove Entry
    3) Find Entry
    4) Quit and save
    '''
    theBook = {}
    readBook(theBook)
    choice = getChoice(theMenu)
    while choice != 4:
        if choice == 1:
            addentry(theBook)
        elif choice == 2:
            removeEntry(theBook)
        elif choice == 3:
            findEntry(theBook)
        else: print "Invalid choice, try again"
        choice = getChoice(theMenu)
    saveBook(theBook)

# Call the main function
if __name__ == "__main__":
    main()
Help me guy's  Some enlightenment and explanation about the wrong and how 
this program works maybe .. I got this code from Alan Gauld tutorial in 
Handling Files part.



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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Dick Moores


At 12:44 AM 6/28/2008, Dick Moores wrote:
At 12:11 AM 6/28/2008, Douglas
Drumond wrote:



But if you don't have l1 defined yet, you can't add to l2

It's like:

def a2():

    l1 = foo +
l2

UnboundLocalError: local variable 'foo' referenced before
assignment

It's because l1 (and foo at above example) is a local variable.

a1's l1 is different from a2's l1.

Sorry to be dense, but how, in what way, is a1's l1  different
from a2's l1"?  Both are [1,2,3]*100 .


Both contain same value, but are in different namespaces (so, different
context and different memory areas).
If you do a="spam" and b="spam", this doesn't make
them same variable, they just have same value.
So is in that code. But to make it more confusing, names were the
same.
No I didn't mean that they were the same variable, but that they had the
same value, and both appear in the same form just below the  
if __name__ == '__main__':   below their respective
functions.
Dick



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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Alan Gauld


"Dick Moores" <[EMAIL PROTECTED]> wrote


I'm puzzled by the below error msg. If I change the line in a2() 
from


l1 = [1,2,3]*100


This is not in a2() this is in the global namespace outside of a2.
a2() consists of a single assignment statement. And assignment
inside a function creates a local variable which in this case
masks the global variable. But the local variable assignment
uses the same variable which is not allowed so you get the
error message.


Why? And why isn't that line a problem for a1()?


In a1 you don't assign so you never create a local variable
you use the global variable



=
def a1():
   return l1.extend(l2)


No assignment, it returns the global value


if __name__=='__main__':
   l1 = [1,2,3]*100
   t = Timer("a1()", "from __main__ import a1")




def a2():
   l1 += l2


new local variable "created" but erroneously. Change to

def a2():
global I1
I1 += I2
return I1

See my tutor topic on namespaces for more on this theme.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



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


Re: [Tutor] addressbook program

2008-06-28 Thread Alan Gauld

"Danny Laya" <[EMAIL PROTECTED]> wrote


Hi I am making an addressBook program now,
and you know some problem, the program doesn't
work.


Always describe the error and, if possible, send the
error text. Python error messages may seem cryptic to
a beginner but they are actually very informative once
you get used to them!

But I'll take a guess...

def readBook(book)
  import os
  if os.path.exists(filename):
  store = open(filename,'r')

The lines under the if statement should be indented.
It may just be email messing things up but since the
rest were OK I'm guessing that this is the error.
Like this:

def readBook(book):
   import os
   if os.path.exists(filename):
  store = open(filename,'r')
  for line in store:
 name = line.rstrip()
 entry = store.next().rstrip()
 book[name] = entry
  store.close()


Remember that indentation(spacing) is all important
in Python, its how python knows how much or how
little to do as a result of the if test or inside the for loop.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld





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


[Tutor] Is "var = None" in Python equivalent to "Set var = Nothing" in VB?

2008-06-28 Thread Kelie
Hello, 

Suppose var holds a reference to an objeect, my question is in the subject. 

Thanks!

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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread wesley chun
> Sorry to be dense, but how, in what way, is a1's l1  different from a2's
> l1"?  Both are [1,2,3]*100 .

dick,

alan and everyone else are correct, but let me just put it as simply as this:

- in a1(), you're accessing l1 as a global variable
- in a2(), you're making l1 a local variable but trying to get its
value before you've assigned anything to it.

i can see what you're trying to do however... a noble effort: answer
the question of whether list contatenation is really slower than using
the extend() method.

anyway, if you make alan's tweak and slip "global l1" as the 1st line
in a2(), it should work better and be a more equivalent comparison.

best of luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
 http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Dick Moores

At 01:05 AM 6/28/2008, Alan Gauld wrote:


"Dick Moores" <[EMAIL PROTECTED]> wrote



I'm puzzled by the below error msg. If I change the line in a2() from

l1 = [1,2,3]*100


This is not in a2() this is in the global namespace outside of a2.
a2() consists of a single assignment statement. And assignment
inside a function creates a local variable which in this case
masks the global variable. But the local variable assignment
uses the same variable which is not allowed so you get the
error message.


Why? And why isn't that line a problem for a1()?


In a1 you don't assign so you never create a local variable
you use the global variable



=
def a1():
   return l1.extend(l2)


No assignment, it returns the global value


if __name__=='__main__':
   l1 = [1,2,3]*100
   t = Timer("a1()", "from __main__ import a1")




def a2():
   l1 += l2


new local variable "created" but erroneously. Change to

def a2():
global I1
I1 += I2
return I1

See my tutor topic on namespaces for more on this theme.


Thanks very much Alan. I think I've got it now, but I will study that 
section in your tutorial.


And my thanks also to Douglas Drumond.

>>> import this
[snip]
Namespaces are one honking great idea -- let's do more of those!
>>>

Dick 


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


[Tutor] need help with a regular expression

2008-06-28 Thread Kelie
Hello,

I'm trying to write a regular expression to filter strings that meet the
following criteria:

1. Starts with 0-3 underscores;
2. Followed by one letter;
3. Then followed by 0 or more letters or digits or hyphens('-'), 
4. Ends with one letter or digit; and
5. There should not be more than one continuous hyphens.

This is what I have so far. I think it meets all the criteria except for the
last one. Haven't figured out the answer yet.

re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]')

Thank you.

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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Martin Walsh
Douglas Drumond wrote:
> 
> In a2() you do l1 += l2, ie, l1 = l1 + l2

A subtle clarification is warranted I think. l1 += l2 is not the same as
l1 = l1 + l2, when l1 and l2 are lists. l1 += l2 is an augmented
assignment statement, and as such will perform the operation in place if
possible, IIUC. Consider the following:

In [1]: l1 = l2 = [1, 2, 3]

In [2]: l1 is l2
Out[2]: True

In [3]: l1 += [4, 5, 6] # in-place

In [4]: l1 is l2
Out[4]: True

In [5]: l1 = l1 + [7, 8, 9] # not

In [6]: l1 is l2
Out[6]: False

Perhaps there is a better reference, but this behavior is discussed
briefly here: http://docs.python.org/ref/augassign.html

> But if you don't have l1 defined yet, you can't add to l2
> It's like:
> def a2():
> l1 = foo + l2
> 
> 
> UnboundLocalError: local variable 'foo' referenced before assignment
> 
> It's because l1 (and foo at above example) is a local variable.
> a1's l1 is different from a2's l1.
Yes, but as Alan pointed out it's considered local because of the
assignment attempt. Obligatory doc reference:
http://www.python.org/doc/2.4/ref/naming.html

snip = """\
If a name binding operation occurs anywhere within a code block, all
uses of the name within the block are treated as references to the
current block. This can lead to errors when a name is used within a
block before it is bound. This rule is subtle. Python lacks declarations
and allows name binding operations to occur anywhere within a code
block. The local variables of a code block can be determined by scanning
the entire text of the block for name binding operations.
"""

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


Re: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB?

2008-06-28 Thread Alan Gauld


"Kelie" <[EMAIL PROTECTED]> wrote

Suppose var holds a reference to an objeect, my question is in the 
subject.


Pretty much so, yes.
There may be very subtle differences due to how Python and VB
treat variables but the basic intent is the same

Alan G 



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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Dick Moores

At 02:22 AM 6/28/2008, Martin Walsh wrote:

Douglas Drumond wrote:
>
> In a2() you do l1 += l2, ie, l1 = l1 + l2

A subtle clarification is warranted I think. l1 += l2 is not the same as
l1 = l1 + l2, when l1 and l2 are lists.


And wow, can the times for each differ from each other! See, for 
example, 


Dick 


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


[Tutor] addressbook program

2008-06-28 Thread Danny Laya

Hi I am making an addressBook program now, and you know ... another error 
message , the program doesn't work. This is the code :

# Loading the addressbook
filename = "addbook.dat"

def readBook(book)
    import os
    if os.path.exists(filename):
    store = open(filename,'r')
    for line in store:
        name = line.rstrip()
        entry = store.next().rstrip()
        book[name] = entry
    store.close()

# Saving the address book
def saveBook(book):
    store = open(filename,"w")
    for name,entry in book.items():
        store.write(name +
 '\n')
        store.write(entry + '\n')
    store.close()

# Getting User Input 
def getChoice(menu):
    print menu
    choice = int(raw_input("Select a choice(1-4): "))
    return choice

# Adding an entry
def addEntry(book):
    name = raw_input("Enter a name: ")
    entry = raw_input("Enter a street, town and phone number: ")
    book[name] = entry

# Removing an entry
def removeEntry(book):
    name = raw_input("Enter a name: ")
    del(book[name])

#Finding an Entry
def findEntry(book):
    name = raw_input("Enter a name: ")
    if name in book:
        print name, book[name]
    else: print "Sorry, no entry for: ", name

#
 Quitting the program
def main():
    theMenu = '''
    1) Add Entry
    2) Remove Entry
    3) Find Entry
    4) Quit and save
    '''
    theBook = {}
    readBook(theBook)
    choice = getChoice(theMenu)
    while choice != 4:
        if choice == 1:
            addentry(theBook)
        elif choice == 2:
            removeEntry(theBook)
        elif choice == 3:
            findEntry(theBook)
        else: print "Invalid choice, try again"
        choice =
 getChoice(theMenu)
    saveBook(theBook)

# Call the main function
if __name__ == "__main__":
    main()
Help me guy's  Some enlightenment and explanation about the wrong and how 
this program works  .. I got this code from Alan Gauld tutorial in Handling 
Files part.

And o...yeah the error message is :

 File "addressbook.py", line 4
    def readBook(book)
 ^
SyntaxError: invalid syntax





  


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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread Dick Moores

At 01:52 AM 6/28/2008, wesley chun wrote:

> Sorry to be dense, but how, in what way, is a1's l1  different from a2's
> l1"?  Both are [1,2,3]*100 .

dick,

alan and everyone else are correct, but let me just put it as simply as this:

- in a1(), you're accessing l1 as a global variable
- in a2(), you're making l1 a local variable but trying to get its
value before you've assigned anything to it.

i can see what you're trying to do however... a noble effort: answer
the question of whether list concatenation is really slower than using
the extend() method.


And in fact, list concatenation seems a bit faster.


anyway, if you make alan's tweak and slip "global l1" as the 1st line
in a2(), it should work better and be a more equivalent comparison.


It does work.

BTW I see that your book has what seems to be a thorough discussion 
of namespaces and variable scopes in chapter 12.


Thanks,

Dick


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


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Dick Moores
On Sat, Jun 28, 2008 at 2:15 AM, Kelie <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm trying to write a regular expression to filter strings that meet the
> following criteria:
>
> 1. Starts with 0-3 underscores;
> 2. Followed by one letter;
> 3. Then followed by 0 or more letters or digits or hyphens('-'),
> 4. Ends with one letter or digit; and
> 5. There should not be more than one continuous hyphens.

Hi Kelie,

I'm not sure of your 5th condition. Do you mean, "A hyphen should not
be immediately followed by a hyphen"? Could you give examples of what
you will permit, and will not permit?

Dick Moores

> This is what I have so far. I think it meets all the criteria except for the
> last one. Haven't figured out the answer yet.
>
> re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]')
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] addressbook program

2008-06-28 Thread bhaaluu
Hello Danny,

Part of learning to program a computer is learning how to solve problems.
I copy/pasted this code directly from the email, and tried to run it, as is.
Error messages in Python are very informative. See below.

On Sat, Jun 28, 2008 at 3:31 AM, Danny Laya <[EMAIL PROTECTED]> wrote:
> Hi I am making an addressBook program now, and you know some problem, the
> program doesn't work. This is the code :
> 
> # Loading the addressbook
> filename = "addbook.dat"
>
> def readBook(book)
> import os
> if os.path.exists(filename):
> store = open(filename,'r')
> for line in store:
> name = line.rstrip()
> entry = store.next().rstrip()
> book[name] = entry
> store.close()

The first error I got was:

File "xyz.py", line 4
  def readBook(book)
   ^
SyntaxError: invalid syntax

shell returned 1

Press ENTER or type command to continue

The error message pointed me to line 4
and the carot (^) pointed to the end of  def readBook(book)

Can you see the error?
You forgot a colon (:) at the end of the def funcName():

Putting a colon there eliminates that error. One down, more to go

>
> # Saving the address book
> def saveBook(book):
> store = open(filename,"w")
> for name,entry in book.items():
> store.write(name + '\n')
> store.write(entry + '\n')
> store.close()

The next error I get is:

File "xyz.py", line 7
  store = open(filename,'r')
  ^
IndentationError: expected an indented block

shell returned 1

Press ENTER or type command to continue

What's the first thing I look at? Which line is the error on?
The error message says it's on line 7. The carot points to
store. The actual message says it is an indentation error.
Fix the indentation.
One more error eliminated...

and so on.. Fix them one at a time, until the program works.
You must have some patience, put in some work, and maybe,
with a little luck, you can learn to program your computer!

Don't give up! Keep trying! You certainly know more than you did
when you started!

What other errors are you getting?

>
> # Getting User Input
> def getChoice(menu):
> print menu
> choice = int(raw_input("Select a choice(1-4): "))
> return choice
>
> # Adding an entry
> def addEntry(book):
> name = raw_input("Enter a name: ")
> entry = raw_input("Enter a street, town and phone number: ")
> book[name] = entry
>
> # Removing an entry
> def removeEntry(book):
> name = raw_input("Enter a name: ")
> del(book[name])
>
> #Finding an Entry
> def findEntry(book):
> name = raw_input("Enter a name: ")
> if name in book:
> print name, book[name]
> else: print "Sorry, no entry for: ", name
>
> # Quitting the program
> def main():
> theMenu = '''
> 1) Add Entry
> 2) Remove Entry
> 3) Find Entry
> 4) Quit and save
> '''
> theBook = {}
> readBook(theBook)
> choice = getChoice(theMenu)
> while choice != 4:
> if choice == 1:
> addentry(theBook)
> elif choice == 2:
> removeEntry(theBook)
> elif choice == 3:
> findEntry(theBook)
> else: print "Invalid choice, try again"
> choice = getChoice(theMenu)
> saveBook(theBook)
>
> # Call the main function
> if __name__ == "__main__":
> main()
> 
> Help me guy's  Some enlightenment and explanation about the wrong and
> how this program works maybe .. I got this code from Alan Gauld tutorial
> in Handling Files part.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Lie Ryan
Filter it. Use two re, one the one you've made, the other the double
hyphen filter:

pat2 = re.compile('.*?\-\-.*?')

If the string matches this re, then the string is rejected, if it DOES
NOT match (i.e. pat2.match('blah') returns None, i.e. if not
pat2.match('blah')), then it is accepted.

btw: You don't care about small letter?

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


[Tutor] How to print numbers in scientific notation form?

2008-06-28 Thread Dick Moores
%.4g comes close to what I want, but no cigar. In the examples below, 
the first 2 are not scientific notation form.


>>> print "%.4g" % 5.09879870978
5.099
>>> print "%.4g" % .0009874345
0.0009874
>>> print "%.4g" % .09878
9.878e-006
>>> print "%.4g" % 187686876876238746
1.877e+017

How can I print all numbers in scientific notation form, and 
designate the number of significant digits?


Thanks,

Dick Moores

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


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Andre Engels
On Sat, Jun 28, 2008 at 11:15 AM, Kelie <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm trying to write a regular expression to filter strings that meet the
> following criteria:
>
> 1. Starts with 0-3 underscores;
> 2. Followed by one letter;
> 3. Then followed by 0 or more letters or digits or hyphens('-'),
> 4. Ends with one letter or digit; and
> 5. There should not be more than one continuous hyphens.
>
> This is what I have so far. I think it meets all the criteria except for the
> last one. Haven't figured out the answer yet.
>
> re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]')

I think

_{0,3}[A-Z](\-?[A-Z0-9])+

will do what you are looking for.


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644 -- Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to print numbers in scientific notation form?

2008-06-28 Thread Cédric Lucantis
Le Saturday 28 June 2008 14:55:04 Dick Moores, vous avez écrit :
> %.4g comes close to what I want, but no cigar. In the examples below,
> the first 2 are not scientific notation form.
>
>  >>> print "%.4g" % 5.09879870978
>
> 5.099
>
>  >>> print "%.4g" % .0009874345
>
> 0.0009874
>
>  >>> print "%.4g" % .09878
>
> 9.878e-006
>
>  >>> print "%.4g" % 187686876876238746
>
> 1.877e+017
>
> How can I print all numbers in scientific notation form, and
> designate the number of significant digits?

%g automatically choose the more readable form. Use %e for that:

 '%e' % 1.0
'1.00e+00'

and to set the number of significant digits (it seems to only set the number 
of digits after the comma, so you have to subtract 1 from it) :

>>> '%.3e' % 1.0
'1.000e+00'

-- 
Cédric Lucantis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Lie Ryan
>> Hello,
>>
>> I'm trying to write a regular expression to filter strings that
meet 
>  the
>> following criteria:
>>
>> 1. Starts with 0-3 underscores;
>> 2. Followed by one letter;
>> 3. Then followed by 0 or more letters or digits or hyphens('-'),
>> 4. Ends with one letter or digit; and
>> 5. There should not be more than one continuous hyphens.
>>
>> This is what I have so far. I think it meets all the criteria
except 
>  for the
>> last one. Haven't figured out the answer yet.
>>
>> re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]')
> 
> I think
> 
> _{0,3}[A-Z](\-?[A-Z0-9])+
> 
> will do what you are looking for.

That, doesn't allow single hyphen, which his requirement allowed as long
as it (the hypehn) is not as the first or last character.

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


Re: [Tutor] How to print numbers in scientific notation form?

2008-06-28 Thread Dick Moores

At 06:17 AM 6/28/2008, Cédric Lucantis wrote:


 '%e' % 1.0
'1.00e+00'

and to set the number of significant digits (it seems to only set the number
of digits after the comma, so you have to subtract 1 from it) :

>>> '%.3e' % 1.0
'1.000e+00'


Perfect! Thanks.

Dick


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


Re: [Tutor] addressbook program

2008-06-28 Thread Kent Johnson
On Sat, Jun 28, 2008 at 6:30 AM, Danny Laya <[EMAIL PROTECTED]> wrote:
>
> Hi I am making an addressBook program now, and you know ... another
> error message , the program doesn't work. This is the code :
> 
> # Loading the addressbook
> filename = "addbook.dat"
>
> def readBook(book)

Missing a colon at the end of this line.

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


Re: [Tutor] How to print numbers in scientific notation form?

2008-06-28 Thread Alan Gauld


"Dick Moores" <[EMAIL PROTECTED]> wrote 


>>> print "%.4g" % 5.09879870978
5.099
>>> print "%.4g" % .09878
9.878e-006

How can I print all numbers in scientific notation form, and 
designate the number of significant digits?


use %e instead of %g

Alan G

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


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Andre Engels
On Sat, Jun 28, 2008 at 3:21 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:

> > I think
> >
> > _{0,3}[A-Z](\-?[A-Z0-9])+
> >
> > will do what you are looking for.
>
> That, doesn't allow single hyphen, which his requirement allowed as long
> as it (the hypehn) is not as the first or last character.

The \-? allows a hyphen, doesn't it?



-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644 -- Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Lie Ryan
On Sat, 2008-06-28 at 17:39 +0200, Andre Engels wrote:
> On Sat, Jun 28, 2008 at 3:21 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:
> 
> > > I think
> > >
> > > _{0,3}[A-Z](\-?[A-Z0-9])+
> > >
> > > will do what you are looking for.
> >
> > That, doesn't allow single hyphen, which his requirement allowed as long
> > as it (the hypehn) is not as the first or last character.
> 
> The \-? allows a hyphen, doesn't it?
> 

Oh, right... when I tested it, I was using small caps, which is why it
doesn't match. But it do have a curious behavior with double dash, when
it met double underscore it cuts the matched string:

>>> s = '__ABC--DE'
>>> pat.match(s).group()
'__ABC'

I think it's because __ABC do match the required pattern. And match's
behavior is to check whether the beginning of the string matches the
pattern, it doesn't care if there is extra character after that.


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


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Mark Tolonen


"Kelie" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Hello,

I'm trying to write a regular expression to filter strings that meet the
following criteria:

1. Starts with 0-3 underscores;
2. Followed by one letter;
3. Then followed by 0 or more letters or digits or hyphens('-'),
4. Ends with one letter or digit; and
5. There should not be more than one continuous hyphens.

This is what I have so far. I think it meets all the criteria except for 
the

last one. Haven't figured out the answer yet.

re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]')



In rule 4, does the string end with an *additional* letter or digit?  The 
string 'A' would seem to fit the rules, but the example provided would fail.


re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*[A-Z0-9]$')   # if rule 4 is an 
additional letter or digit
re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*(?single-letter strings are allowed


-Mark 



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


Re: [Tutor] "local variable 'l1' referenced before assignment"

2008-06-28 Thread wesley chun
>  BTW I see that your book has what seems to be a thorough discussion of
> namespaces and variable scopes in chapter 12.

ah, that section (12.3) you're referring to is mostly about namespaces
as it's in the Modules chapter.  the real bit about variable scope
that you're seeking is actually in the immediately preceding chapter
on Functions in section 11.8, which does address some of the topics
covered in this thread. the reason why scope is mentioned in that ch12
section is because i introduce namespaces there, and it's easy for
those new to the language to get confused about the relationship b/w
namespaces and variable scope.

for example, and this is not recommended, of course, create a global
variable named 'str', then create another one in a function, like
this:

str = 'foo'
def func():
str = 'bar'

so now the name 'str' lives in *3* different namespaces, local (to
func), global, and built-in. *but* from any point in your code, you
only have (legal) access to one of them -- that's scope. (side note: i
think 'str' and 'list' are the 2 most popular variables that
shadow/override built-in names.)

one thing that i did learn from all you tutors is the behavior for
augmented asst differing from that of the full asst syntax... i'll jot
down to make sure it's covered in the next edition.  :-)

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Python in Windows

2008-06-28 Thread wesley chun
>  IDLE 1.2.2
>  >>> from gasp import *
>
>  Traceback (most recent call last):
>   File "", line 1, in 
>from gasp import *
>  ImportError: No module named gasp


as brian mentioned, gasp doesn't come with Python.  in fact, this very
thread came up just last month, and here was one of my replies, but
you can also check out the entire thread if you wish:

http://mail.python.org/pipermail/tutor/2008-May/061975.html

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] addressbook program

2008-06-28 Thread Alan Gauld

"FT" <[EMAIL PROTECTED]> wrote


#Copying the Address Book With New Name!
def copy_Book (book):
save = 1
file_name2 = text_Input(" Enter Name Of File To Save Address 
Book:")

if file_name2 == "":
print "No File Saved!"
   save = 0
if save == 1:
   try:
   store = open(file_name2, 'w')
except:
   print "File Error! No File Saved!"
   save = 0
   if save == 1:
   for name,entry in book.items():
   store.write(name + '\n')
   store.write(entry + '\n')
   store.close()
   print "%s File Saved and Closed!" % file_name2


This is unnecessarily complex. By rearranging the logic slightly we
can write it as:

def copy_Book (book):
file_name2 = text_Input(" Enter Name Of File To Save Address 
Book:")

if file_name2:
   try:
  store = open(file_name2, 'w')
  for name,entry in book.items():
 store.write(name + '\n')
 store.write(entry + '\n')
  store.close()
  print "%s File Saved and Closed!" % file_name2
   except:
   print "File Error! No File Saved!"
   return

However, I'd prefer to pass the filename in as an argument since
mixing processing and user interaction is usually a bad idea.
Also in the tutorial I don't use try/except because I haven't
covered them yet!


#Getting User Input
def get_Choice( menu, msg=""):
e=1
while e==1:
e=0
try:
choice =  key_input(msg)
except:
choice=0


Again the use of the e flag is making the structure more complex
than is necessary. In Python you can usually avoid the use of
such flags by reworking the logic - often by reversing a boolean
test as I did above.


#DO TEXT INPUT WITH ENTRY ON NEXT LINE!
def text_Input(prompt):
print prompt
return (raw_input(">> "))


Just use:

raw_input(prompt + "\n>> " )


def add_Entry (book):
name = text_Input("Enter a name: ")
if name != "":
entry = text_Input("Enter Street, City/Town and Phone 
Number: ")

   if name != "" and entry != "":
   book[ name.capitalize()] = entry
   else:
print "No entry saved!"


Could be simplified to:

def add_Entry (book):
name = text_Input("Enter a name: ")
entry = text_Input("Enter Street, City/Town and Phone Number: ")
if name and entry:
book[ name.capitalize()] = entry
else:
print "No entry saved!"



def key_input( msg):
"ENTER A KEY OR FUNCTION KEY, (ALT, CTRL, SHIFT...KEY)"
# clear the keyboard buffer
ch=""; ch1=""; sch=""
while msvcrt.kbhit():
ch = msvcrt.getch()


Given the OP was a novice I suspect this might be a tad advanced
at this stage :-)

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



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


Re: [Tutor] Using Python in Windows

2008-06-28 Thread Ben
Hmm. The instruction on adding something
gaspthe
library seems to be catered towards Linux. I've done a Google search
and
glanced at the Tutorial, the Windows FAQ (
http://www.python.org/doc/faq/windows/), ect. I don't see it in the global
module index . Installing Python
modules  goes a little over my
head...

On Sat, Jun 28, 2008 at 1:21 PM, wesley chun <[EMAIL PROTECTED]> wrote:
>>  IDLE 1.2.2
>>  >>> from gasp import *
>>
>>  Traceback (most recent call last):
>>   File "", line 1, in 
>>from gasp import *
>>  ImportError: No module named gasp
>
>
> as brian mentioned, gasp doesn't come with Python.  in fact, this very
> thread came up just last month, and here was one of my replies, but
> you can also check out the entire thread if you wish:
>
> http://mail.python.org/pipermail/tutor/2008-May/061975.html
>
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Create file and input text

2008-06-28 Thread David
Hi, I am very new to python and it is my first attempt at programing 
except for some basic bash scripts. I came up with this;

#!/usr/bin/python

import os
filename = raw_input('Enter the filename: ')
fobj = open(filename, 'w')
yourname = raw_input('What is your name: ')
fobj.write(yourname)
fobj.close()

It seems to work Ok, I was shocked! Is it OK?

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

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


Re: [Tutor] addressbook program

2008-06-28 Thread FT

Hi Alan,

You said:
> #DO TEXT INPUT WITH ENTRY ON NEXT LINE!
> def text_Input(prompt):
> print prompt
> return (raw_input(">> "))

Just use:

raw_input(prompt + "\n>> " )

Yes, that is OK if you are sighted, for the screen reader program does
not say the message in the prompt unless there is some kind of a change in
the screen.
I have to place it there for only a sightless programmer. Maybe once in
a while it would say it, but that is if the key stroke is fast and the kill
speech is quick. Like the purge command inside the example, when that is set
for all key strokes in a screen reader, it can erase any saying of text
displayed fast onto the screen, just a timing issue between keyboard and
screen reader capture.
So, my example is just accommodating that.

The other examples are true, I sent it without making the needed
changes. Probably too many try statements only because I wrote an input for
my Trek program that entered values of a given type and kind of left it
there if the wrong type is entered. Which brings up the other dictionary
list of keys. Just left it there when sending the example to fast. Just like
the last method which uses pygame, but it is never called and would fail
since I did not import pygame.

So, sending an outdated example is not good, but does lead to showing
the correct sample in a tutorial when you point out errors or sloppy work.

Thanks, Bruce

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


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Kelie
Dick Moores  gmail.com> writes:

> I'm not sure of your 5th condition. Do you mean, "A hyphen should not
> be immediately followed by a hyphen"? Could you give examples of what
> you will permit, and will not permit?

Dick, your are correct. A hyphen should not be immediately followed by a hyphen.
Actually I forgot another criteria that all letters should be uppercase. Here is
the revised criteria:

1. Starts with 0-3 underscores;
2. Followed by one letter;
3. Then followed by 0 or more letters or digits or hyphens('-'), 
4. There should not be more than one continuous hyphens;
5. The last character should be letter or digit; and
6. All letters should be uppercase.

These are some examples:

G-ANNO-SYMB is good;
-G-ANNO-SYMB is bad;
_G-ANNO-SYMB is good;
_TEMP is good;
TEMP is bad; (4 leading underscores);
c-n-cen is bad; 
C-N-CEN is good;
C-N-BLDG1 is good;
C_N-BLDG1 is bad;
C N BLDG is bad;
1 is bad;
_1-TEXT is bad;
_TEXT-1 is good.

Thanks.



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


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Kelie
Mark Tolonen  gmail.com> writes:
> re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*[A-Z0-9]$')   # if rule 4 is an 
> additional letter or digit
> re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*(? single-letter strings are allowed
> 

Mark, single-letter strings are allowed and your regular expression works as
expected. Thank you!





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


[Tutor] need help; save web data

2008-06-28 Thread Michael Miesner
Hi all-
I am trying to save the output of a web search to a local file, using
python.
Im really new to this, but I want to be able to write a program that uses
google scholar, but takes search results and saves them to a local file.
I am perfectly fine with playing around wtih this until I get it, but I dont
know how to begin to get python to grab the output of a given search on
google scholar and save it to a file.

Thanks for all your help.

Michael

-- 

Michael Miesner
PHDC in Clinical Psychology
East Tennessee State University
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] arrays in python

2008-06-28 Thread Kirk Z Bailey
Just wondering, if I can find a way to do a 2 dimensional array in 
python. 1 dimension would be a list it would seem; for 2, I could use a 
list of lists?


Strange how I can't think of ever needing one since I discovered snake 
charming, but so many languages do foo dimensional arrays, it would seem 
like there ought to be a way to do it in python.


--
end

Very Truly yours,
 - Kirk Bailey,
   Largo Florida

   kniht
  +-+
  | BOX |
  +-+
   think
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Python in Windows

2008-06-28 Thread wesley chun
> Hmm. The instruction on adding something gasp the library seems to be
> catered towards Linux.


hmmm, you are correct, and apparently, this is a popular question to
the maintainers (note these links are circular):
https://answers.launchpad.net/gasp-code/+question/36144
https://answers.launchpad.net/gasp-code/+question/17174
https://answers.launchpad.net/gasp-code/+faq/28

however, i *did* find out that GASP is in the cheeseshop:
http://pypi.python.org/pypi/gasp/0.4.5

sooo, what does this mean? it means if you install EasyInstall...
http://peak.telecommunity.com/DevCenter/EasyInstall
http://peak.telecommunity.com/DevCenter/EasyInstall#windows-notes (NOTE!)

..., then installing GASP would be as easy as opening up a Command/DOS
window and issuing:
C:\> easy_install gasp

you'll see some output like:
Searching for gasp
Reading http://pypi.python.org/simple/gasp/
Reading http://dc.ubuntu-us.org/bazaar/gasp
Best match: gasp 0.4.5
Downloading http://pypi.python.org/packages/2.5/g/gasp/gasp-0.4.5-py2.5.egg
Processing gasp-0.4.5-py2.5.egg
creating c:\python25\lib\site-packages\gasp-0.4.5-py2.5.egg
Extracting gasp-0.4.5-py2.5.egg to c:\python25\lib\site-packages
 :

you'll find that EasyInstall is a great tool to have because you can
continue to use it to install other Python related software moving
forward, all in a similarly "easy" manner.

good luck!
-wesley
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Create file and input text

2008-06-28 Thread wesley chun
> Hi, I am very new to python and [...] came up with this;

>  #!/usr/bin/python
 >
 >  import os
 >  filename = raw_input('Enter the filename: ')
 >  fobj = open(filename, 'w')
 >  yourname = raw_input('What is your name: ')
 >  fobj.write(yourname)
 >  fobj.close()
 >
 >  It seems to work Ok, I was shocked! Is it OK?



david,

 welcome to Python!  u, yes, it is ok.  your syntax is perfect, and
 it should've done exactly what you wanted.  and yes, Python is *that*
 intuitive and that easy. you're gonna *love* programming with it.  :-)

 one suggestion i *do* have is that your code only writes a single line
 of text to the file. if you intend on creating a text file with
 multiple lines, be sure to add a NEWLINE (\n) at the end of each
 string, otherwise you'll be writing everything all to one single,
 really long line.

 another idea is that you may wish to write some code that does the
 opposite: open a text file for read, display its contents, close the
 file, just as a test to ensure that your original app works as
 advertised.

 cheers!
 -- wesley
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 "Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

 wesley.j.chun :: wescpy-at-gmail.com
 python training and technical consulting
 cyberweb.consulting : silicon valley, ca
 http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Create file and input text

2008-06-28 Thread Danny Yoo
>>  #!/usr/bin/python
>  >
>  >  import os
>  >  filename = raw_input('Enter the filename: ')
>  >  fobj = open(filename, 'w')
>  >  yourname = raw_input('What is your name: ')
>  >  fobj.write(yourname)
>  >  fobj.close()
>  >
>  >  It seems to work Ok, I was shocked! Is it OK?

Hi David,

The first line, the import of the 'os' module, is superfluous: it's
not being used.


>  welcome to Python!  u, yes, it is ok.  your syntax is perfect, and
>  it should've done exactly what you wanted.  and yes, Python is *that*
>  intuitive and that easy. you're gonna *love* programming with it.  :-)

Python won't let you break any laws of gravity.  But there are a lot
of good people here on Tutor who will be happy to be of assistance
when the programs get harder to write.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Create file and input text

2008-06-28 Thread wesley chun
>  The first line, the import of the 'os' module, is superfluous: it's
>  not being used.

oops, good catch danny... i didn't even see that.


> Python won't let you break any laws of gravity.  But there are a lot
>  of good people here on Tutor who will be happy to be of assistance
>  when the programs get harder to write.

well, like with all functionality, you just have to import the right module:
http://xkcd.com/353/

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


Re: [Tutor] arrays in python

2008-06-28 Thread Mark Tolonen


"Kirk Z Bailey" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Just wondering, if I can find a way to do a 2 dimensional array in python. 
1 dimension would be a list it would seem; for 2, I could use a list of 
lists?


Strange how I can't think of ever needing one since I discovered snake 
charming, but so many languages do foo dimensional arrays, it would seem 
like there ought to be a way to do it in python.


Yes, use lists of lists, but be careful constructing them:

 >>> L=[[0]*5]*5
 >>> L
 [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]

 >>> L[0][0]=1
 >>> L
 [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 
0, 0, 0, 0]]


Oops, five references to the same list.  Changing one changes all.

 >>> L=[[0]*5 for _ in range(5)]
 >>> L
 [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]

 >>> L[0][0]=1
 >>> L
 [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]


Use a list comprehension to construct five different lists.

--Mark


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