Re: [Tutor] deck dealing program

2005-08-08 Thread python-tutor
Are you:
  a.) Having trouble with the code and looking for help?
  b.) Looking for suggestions on how to improve the code?
  c.) Offering the code as a demo for Nathan et al.?

I was just doing stuff along the same lines and was having fun seeing the 
different approaches to the same problem.  

--Todd 

On Monday 08 August 2005 02:38 am, luke wrote:
> from random import randint
>
> def identify_card(n):
> cardname = ""
> royals = ["Jack","Queen","King","Ace"]
> temp = n % 13
> if temp > 8:
> cardname += royals[temp-9]
> else:
> cardname += str(temp+2)
> cardname += " of "
>
> suits = ["Spades","Hearts","Diamonds","Clubs"]
> cardname += suits[n/13]
> return cardname
>
> def main():
> deck = range(52)
> cards = []
> while 1:
> x = raw_input("how many cards do you want? ")
> try:
> x = int(x)
> except ValueError:
> print "Invalid value exiting for I have no error code. Please
> use an int next time." raise SystemExit
> if x <= 52 and x >= 0:
> y = 0
> while y < x:
>
> cards.append(identify_card(deck.pop(randint(0,len(deck)-1 y += 1
> break
> print cards
> if __name__ == "__main__":
> main()
>
> #Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question About chdir()

2005-08-08 Thread Don Parris
The book, "Programming Python", shows an example of os.chdir() on the
Windows platform, as follows:

os.chdir(r'c:\temp')

What's the 'r' for?  It didn't seem to make any difference in how
Python works - at least not on the surface.

Thanks,
Don
-- 
DC Parris GNU Evangelist
http://matheteuo.org/
[EMAIL PROTECTED]
"Hey man, whatever pickles your list!"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question About chdir()

2005-08-08 Thread Ewald Ertl
Hi Don!

Don Parris wrote:
> The book, "Programming Python", shows an example of os.chdir() on the
> Windows platform, as follows:
>
> os.chdir(r'c:\temp')


r ... raw Strings. There will no substitution be processed.
Otherwise the "\t" ( Tab ) will be inserted in the string:


>>> print "a\tb"
a   b
>>> print r"a\tb"
a\tb
>>>


HTH Ewald

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


Re: [Tutor] Question About chdir()

2005-08-08 Thread python-tutor
Let's see if I can get this right.as I am working on memory and not enough 
sleep.

The 'r' means that using a raw string so the backslashes aren't escaped 
out

The equivalent without using the 'r' would be: os.chdir('c:\\temp')

--Todd

On Monday 08 August 2005 03:07 am, Don Parris wrote:
> The book, "Programming Python", shows an example of os.chdir() on the
> Windows platform, as follows:
>
> os.chdir(r'c:\temp')
>
> What's the 'r' for?  It didn't seem to make any difference in how
> Python works - at least not on the surface.
>
> Thanks,
> Don
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Get information from a web page

2005-08-08 Thread David Holland
Hi All,
I am trying to save to disk a webpage (so I can extract useful info) with a urlof type "http://xxx.co.uk/index.php?node=2371&pagetree=&fromid=20397".However the following :-urllib.urlopen, urllib._urlopener, urllib2.Request, urllib2.urlopen,urllib2.urlretrievejust retrieve this webpage :- http://xxx.co.uk (the root page) not the page I wanted to retrieve, any ideas about to get the right page ?
Thanks inadvance
 
David
		Yahoo! Messenger 
 NEW - crystal clear PC to PC 
calling worldwide with voicemail 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Get information from a web page

2005-08-08 Thread python-tutor
Not sure exactly what you have going wrong without the code or the exact url 
you are using.  

Does something like:

import urllib

page = 
urllib.urlopen("http://slashdot.org/article.pl?sid=05/08/08/043236&tid=126";).read()
print page 

give you the correct results?


Is the problem specific to only to that url?

--Todd


On Monday 08 August 2005 04:46 am, David Holland wrote:
> Hi All,
> I am trying to save to disk a webpage (so I can extract useful info) with a
> url of type "http://xxx.co.uk/index.php?node=2371&pagetree=&fromid=20397";.
> However the following :-
> urllib.urlopen, urllib._urlopener, urllib2.Request,
> urllib2.urlopen,urllib2.urlretrieve just retrieve this webpage :-
> http://xxx.co.uk (the root page) not the page I wanted to retrieve, any
> ideas about to get the right page ? Thanks inadvance
>
> David
>
>
> -
> Yahoo! Messenger  NEW - crystal clear PC to PC calling worldwide with
> voicemail
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 18, Issue 41

2005-08-08 Thread David Holland
Looking at the slashdot url works fine, I think the problem is because I am trying to download a page with an address of the form url.php?node=5924&pagetree=&fromid=&objectid=25586
And I only download url not url.phpetc.
Is there anyway that that can be done ?
 
David

Message: 8Date: Mon, 8 Aug 2005 05:11:57 -0400From: [EMAIL PROTECTED]Subject: Re: [Tutor] Get information from a web pageTo: tutor@python.orgMessage-ID: <[EMAIL PROTECTED]>Content-Type: text/plain; charset="iso-8859-6"Not sure exactly what you have going wrong without the code or the exact url you are using. Does something like:import urllibpage = urllib.urlopen("http://slashdot.org/article.pl?sid=05/08/08/043236&tid=126").read()print page give you the correct results?Is the problem specific to only to that url?*
		To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] raw string - solution to open_new() problem

2005-08-08 Thread Tom Cloyd
Ewald Ertl's reply to Don Parris's question about "r" operator gave me the  
idea of trying that out to solve my problem with file name scrambling when  
trying to use webbrowser.open_new() to open a file on my computer in a  
browser. It worked!

So, thie

webbrowser.open_new("file://C:\__Library\folders\02394 Yale Style  
Manual\02394 Yale_Style_Manual.htm")

does not work, but this

webbrowser.open_new(r"file://C:\__Library\folders\02394 Yale Style  
Manual\02394 Yale_Style_Manual.htm")

does.

Thank you Ewald, for triggering the solution in my mind!

Now, if anyone can explain why webbrowser.open_new() does the character  
substitution thing it was doing (and thus becoming unable to locate the  
file in question), I'm eager to hear it.

Meanwhile, I can go ahead with my program.

-- t.

==
Tom Cloyd, MS MA, LMHC
Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< BestMindHealth.com / [EMAIL PROTECTED] >>
==

Using Opera's revolutionary e-mail client (program):  
http://www.opera.com/mail/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] use of webbrowser.open_new()

2005-08-08 Thread Kent Johnson
Tom Cloyd wrote:
> Having just discovered the webbrowser module, I've confirmed that I can  
> indeed open a URL in my default browser using something like
> 
> webbrowser.get_new("{URL}")
> 
> What I want to do is open a web page stored on my local machine. I'm not  
> getting it to work -
> 
> webbrowser.open_new("C:\__Library\folders\05238 Design for Confusion\05238  
> Design for Confusion -05krugman.html")

The backslash (\) has a special meaning in strings; it means, "interpret the 
next character as a special code". A complete list of the codes is here:
http://docs.python.org/ref/strings.html

So \f means FORM FEED and \052 means the character with octal value 052 which 
happens to be an asterisk.

That is why the file name in the error message looks different from the one you 
wrote.

There are two ways to fix this. First, you can prefix the string with an 'r' 
(for 'raw') which disables most of the \ escapes. This is handy when you are 
copying the file name from Windows Explorer:
webbrowser.open_new(r"C:\__Library\folders\05238 Design for Confusion\05238 
Design for Confusion -05krugman.html")

Alternately you can use / instead of \; this will work fine:
webbrowser.open_new("C:/__Library/folders/05238 Design for Confusion/05238 
Design for Confusion -05krugman.html")

Kent

> Traceback (most recent call last):
>File "C:\Program Files\ActiveState Komodo  
> 3.1\dbgp\pythonlib\dbgp\client.py", line 3149, in runcode
>  locals = self.frame.f_locals)
>File "C:\Program Files\ActiveState Komodo  
> 3.1\dbgp\pythonlib\dbgp\client.py", line 1569, in runcode
>  h_exec(code, globals=globals, locals=locals, module=module)
>File "C:\Program Files\ActiveState Komodo  
> 3.1\dbgp\pythonlib\dbgp\client.py", line 516, in __init__
>  exec code in globals, locals
>File "", line 0, in __main__
>File "C:\Python24\Lib\webbrowser.py", line 46, in open_new
>  get().open(url, 1)
>File "C:\Python24\Lib\webbrowser.py", line 250, in open
>  os.startfile(url)
> WindowsError: [Errno 2] The system cannot find the file specified:  
> 'C:\\__Library\x0colders*38 Design for Confusion*38 Design for Confusion  
> -05krugman.html'
> 
> Can you suggest what I might be doing wrong here?
> 
> -- t.
> 
> ==
> Tom Cloyd
> Bellingham, Washington, U.S.A: (360) 920-1226
> << BestMindHealth.com / [EMAIL PROTECTED] >>
> ==
> 
> Using Opera's revolutionary e-mail client (program):  
> http://www.opera.com/mail/
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

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


Re: [Tutor] Tutor Digest, Vol 18, Issue 41

2005-08-08 Thread Kent Johnson
David Holland wrote:
> Looking at the slashdot url works fine, I think the problem is because I 
> am trying to download a page with an address of the form 
> url.php?node=5924&pagetree=&fromid=&objectid=25586
> And I only download url not url.phpetc.
> Is there anyway that that can be done ?

Please show us some code.

Kent

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


[Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Jan Eden
Hi,

in Perl's DBI, I used fetchrow_hashref() to receive a database row as a 
dictionary, with the field names being the dictionary keys.

MySQLdb's fetchone() returns a tuple Unfortunately, I have a dictionary of SQL 
queries which return rows of different lengths (read: with a varying number of 
fields).

The documentation for MySQLdb says that fetchoneDict() is deprecated and the 
usage of fetchone() is suggested.

Is there a recommended way to receive the results of an SQL query in the form I 
need? Or do I have to create a dictionary of fieldname tuples which can be 
zipped with the query result tuple?

Thanks,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - 
Programming Perl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Kent Johnson
Jan Eden wrote:
> Hi,
> 
> in Perl's DBI, I used fetchrow_hashref() to receive a database row as
> a dictionary, with the field names being the dictionary keys.
> 
> MySQLdb's fetchone() returns a tuple Unfortunately, I have a
> dictionary of SQL queries which return rows of different lengths
> (read: with a varying number of fields).
> 
> The documentation for MySQLdb says that fetchoneDict() is deprecated
> and the usage of fetchone() is suggested.

You could just use fetchoneDict(); deprecated isn't the same as gone...
> 
> Is there a recommended way to receive the results of an SQL query in
> the form I need? Or do I have to create a dictionary of fieldname
> tuples which can be zipped with the query result tuple?

You can create a list of field names from the cursor.description attribute. But 
if the number of fields in the result varies how do you know which field goes 
with which description?

Kent

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


Re: [Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Jan Eden
Kent Johnson wrote on 08.08.2005:

>Jan Eden wrote:

>>The documentation for MySQLdb says that fetchoneDict() is
>>deprecated and the usage of fetchone() is suggested.
>
>You could just use fetchoneDict(); deprecated isn't the same as
>gone...

I tend to avoid deprecated functions/methods - I would need another method 
sooner or later anyway.
>>
>>Is there a recommended way to receive the results of an SQL query
>>in the form I need? Or do I have to create a dictionary of
>>fieldname tuples which can be zipped with the query result tuple?
>
>You can create a list of field names from the cursor.description
>attribute. But if the number of fields in the result varies how do
>you know which field goes with which description?
>
That works, thank you. I will use the cursor.description attribute immediately 
after executing a query, so it will contain the correct field descriptions 
whenever I need them. The rest of my program uses the type attribute to decide 
which fields are present and which are not.

All this is part of a port from Perl to Python - I will publish a log of 
everything I encountered in a couple of weeks.

Cheers,

Jan
-- 
There's no place like ~/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Curses example on Linux?

2005-08-08 Thread Hossein Movahhedian

   Hi All,

   I have copied the following example from "Learning to Program by Alan
 Gauld (section: Event Driven Programming)". To run it on Linux
 (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt'
 with 'curses.stdscr'. But there is no stdscr method in curses.
 In fact with 'import curses.stdscr' I get the following error message::

 Traceback (most recent call last):
   File "", line 1, in ?
 ImportError: No module named stdscr

 How should I modify it for Linux?

Thanks in advance,
Hossein

The example:{{{

import msvcrt

def doKeyEvent(key):
if key == '\x00' or key == '\xe0': # non ASCII
   key = msvcrt.getch() # fetch second character
print ord(key)

def doQuitEvent(key):
raise SystemExit


# First, clear the screen of clutter then warn the user
# of what to do to quit
lines = 25 # set to number of lines in console
for line in range(lines): print

print "Hit space to end..."
print

# Now mainloop runs "forever"
while True:
   ky = msvcrt.getch()
   length = len(ky)
   if length != 0:
  # send events to event handling functions
  if ky == " ": # check for quit event
 doQuitEvent(ky)
  else:
 doKeyEvent(ky)
}}}
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] raw string - solution to open_new() problem

2005-08-08 Thread Terry Carroll
On Mon, 8 Aug 2005, Tom Cloyd wrote:

> So, thie
> 
> webbrowser.open_new("file://C:\__Library\folders\02394 Yale Style  
> Manual\02394 Yale_Style_Manual.htm")
> 
> does not work, but this
> 
> webbrowser.open_new(r"file://C:\__Library\folders\02394 Yale Style  
> Manual\02394 Yale_Style_Manual.htm")

I use forward slashes, it's simpler:

webbrowser.open_new("file://C:/__Library/folders/02394 Yale Style 
Manual/02394 Yale_Style_Manual.htm")


> Now, if anyone can explain why webbrowser.open_new() does the character  
> substitution thing it was doing (and thus becoming unable to locate the  
> file in question), I'm eager to hear it.

Your original contains "\02394 Yale Style".  "\023" equates to an octal 
23 (hex 13, decimal 19), rather than looking for a directory named:

 02394 Yale Style Manual

It's looking for

 X94 Yale Style Manual

Where "X" is actually a character with hex code 0x19.


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


[Tutor] Shut up and deal!

2005-08-08 Thread Greg Lindstrom
I found the conversation of dealing cards interesting, so I took a few
minutes (about 20 while I waited for a production run to finish) and
came up with the following Dealer class.  I come with a long
history of coding in C/C++ and have been told my code looks like it
(notice, in particular the nested "for" loops in the Shuffle
method).  What type of Pythonic changes would make this? 
What features would be nice?  This was just for fun, so let's not
take it too seriously!

--greg

- - - - Start Snippet - - - - - - - - - -
#!/usr/bin/python
from random import shuffle

class Dealer(object):
   # define your deck here
   SUITS = ('Spades', 'Hearts', 'Clubs', 'Diamonds')
   RANKS = ('2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace')

   def __init__(self, decks=1, suits=SUITS, ranks=RANKS):
   self.number_of_decks = decks
   self.suits = suits
   self.ranks = ranks
   self.Shuffle()

   def Shuffle(self):
   self.deck = []
   for deck in range(self.number_of_decks):
   for suit in self.suits:
   for rank in self.ranks:
  
self.deck.append('%s of %s'%(rank,suit))
   shuffle(self.deck)

   def Deal(self):
   '''Return the top card from the deck, or None if the deck is depleated'''
   if len(self.deck) > 0:
  card = self.deck[0]
  del self.deck[0]
  return card
   else:
  return None

###
### Unit Test #
###
if __name__ == '__main__':
   dealer = Dealer()
   for n in range(10):
   print dealer.Deal()

- - - - End Snippet - - - - -

Which yields:
    2 of Clubs
    7 of Diamonds
    9 of Diamonds
  Ace of Diamonds
 Jack of Hearts
 King of Hearts
    8 of Clubs 
 King of Clubs
    5 of Spades
    3 of Hearts



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


[Tutor] Using urllib to retrieve info

2005-08-08 Thread David Holland
Kent,

Sorry I should have put my code.
This is what I wrote
import urllib
import urllib2
f =
urllib.urlopen("http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897";).read()
newfile = open("newfile.html",'w')
newfile.write(f)
newfile.close()
print 'finished'

It runs fine but the file saved to disk is the
information at : 'http://support.mywork.co.uk'
not
'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897";'
(By the way the real url is
http://support.mywork.co.uk
as I don't what my boss to know I am doing this, in
case I can't not get it to work, in which case he will
say a waste of time.  Of course if I do get it to work
it will not be a waste of time).


The bizarre thing is that for an address like :-
'http://www.linuxquestions.org/questions/showthread.php?s=&threadid=316298'.

It works okay.

Does that make sense.
Thanks everyone for the help so far.





___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shut up and deal!

2005-08-08 Thread Kent Johnson
Greg Lindstrom wrote:
> I found the conversation of dealing cards interesting, so I took a few 
> minutes (about 20 while I waited for a production run to finish) and 
> came up with the following Dealer class.  I come with a long history of 
> coding in C/C++ and have been told my code looks like it (notice, in 
> particular the nested "for" loops in the Shuffle method).  What type of 
> Pythonic changes would make this?  What features would be nice?  This 
> was just for fun, so let's not take it too seriously!

It looks pretty good to me; a couple of alternatives suggested below. Oh, and 
typical Python usage is to start method names with lower case letters, e.g. 
shuffle(), deal().

Kent

> 
> --greg
> 
> - - - - Start Snippet - - - - - - - - - -
> #!/usr/bin/python
> from random import shuffle
> 
> class Dealer(object):
># define your deck here
>SUITS = ('Spades', 'Hearts', 'Clubs', 'Diamonds')
>RANKS = 
> ('2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace')
> 
>def __init__(self, decks=1, suits=SUITS, ranks=RANKS):
>self.number_of_decks = decks
>self.suits = suits
>self.ranks = ranks
>self.Shuffle()
> 
>def Shuffle(self):
>self.deck = []
>for deck in range(self.number_of_decks):
>for suit in self.suits:
>for rank in self.ranks:
>self.deck.append('%s of %s'%(rank,suit))

If you don't like the nested for you can use a generator expression with two 
'for' clauses:
  deck.extend('%s of %s'%(rank,suit) for suit in self.suits for rank in 
self.ranks)
though I think your version is clearer.


>shuffle(self.deck)
> 
>def Deal(self):
>'''Return the top card from the deck, or None if the deck is 
> depleated'''
>if len(self.deck) > 0:
>   card = self.deck[0]
>   del self.deck[0]
>   return card
>else:
>   return None

could be
  try:
return self.deck.pop(0)
  except IndexError:
return None

Since you don't really care which end of the deck is dealt you could pop the 
end of the deck (use self.deck.pop()), that avoids having to move all the other 
cards down.

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


[Tutor] while loops

2005-08-08 Thread Will Harris
I am working my way through "python programming for the absolute beginner" and 
one of the challenges is to create a program that will flip a coin 100 times 
and tell you how many of each it did. Now I have it flipping the coin, but when 
I try to do this 100 times I end up with it running through 100 times, but 
always the same result comes back. It will either be 100 heads, or 100 tails. I 
have tried if statements and while loops and both seem to give me all or 
nothing. I am just looking for a hint at the direction to look of adjust to get 
the code below working not really the solution. Thanks in advanced for any tips.

#!/usr/bin/python
import random

coin = random.randrange(2)

count = 0
head_count = 0
tail_count = 0

while (count != 100):
if coin == 0:
print "You got Heads!"
head_count = head_count + 1
count = count + 1
else:
print "You got Tails!"
tail_count = tail_count + 1
count = count + 1

print "Out of", count, "you flipped", head_count, "heads and ", tail_count, 
"tails"

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


Re: [Tutor] Using urllib to retrieve info

2005-08-08 Thread Kent Johnson
David Holland wrote:
> Kent,
> 
> Sorry I should have put my code.
> This is what I wrote
> import urllib
> import urllib2
> f =
> urllib.urlopen("http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897";).read()
> newfile = open("newfile.html",'w')
> newfile.write(f)
> newfile.close()
> print 'finished'
> 
> It runs fine but the file saved to disk is the
> information at : 'http://support.mywork.co.uk'
> not
> 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897";'

There is something strange with this site that has nothing to do with Python. 
Just playing around with the two URLs in Firefox I get different results by 
reloading the page. If I try loading the two URLs with curl, I get the same 
thing for both.

Possibly there is something going on with cookies; you might take a look at 
urllib2 and its support for cookies to see if you can get it working the way 
you want.

Kent

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


Re: [Tutor] while loops

2005-08-08 Thread Kent Johnson
Will Harris wrote:
> I am working my way through "python programming for the absolute
> beginner" and one of the challenges is to create a program that will
> flip a coin 100 times and tell you how many of each it did. Now I
> have it flipping the coin, but when I try to do this 100 times I end
> up with it running through 100 times, but always the same result
> comes back. It will either be 100 heads, or 100 tails. I have tried
> if statements and while loops and both seem to give me all or
> nothing. I am just looking for a hint at the direction to look of
> adjust to get the code below working not really the solution. Thanks
> in advanced for any tips.

You need to change the value of coin inside the loop. The code you have flips 
the coin once and reports the result 100 times.

Kent

> 
> #!/usr/bin/python
> import random
> 
> coin = random.randrange(2)
> 
> count = 0
> head_count = 0
> tail_count = 0
> 
> while (count != 100):
> if coin == 0:
> print "You got Heads!"
> head_count = head_count + 1
> count = count + 1
> else:
> print "You got Tails!"
> tail_count = tail_count + 1
> count = count + 1
> 
> print "Out of", count, "you flipped", head_count, "heads and ", tail_count, 
> "tails"
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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


Re: [Tutor] while loops

2005-08-08 Thread Jay Loden
> coin = random.randrange(2)

That's the problem there...you've got coin assigned outside the while loop, so 
it is assigned 0 or 1 once, before the loop, and then you're running 100 
checks on the same value. 

If you move 
> coin = random.randrange(2)

to inside the while loop before the if statement, you'll get the result you 
want. 

-Jay


On Monday 08 August 2005 5:41 pm, Will Harris wrote:
> I am working my way through "python programming for the absolute beginner"
> and one of the challenges is to create a program that will flip a coin 100
> times and tell you how many of each it did. Now I have it flipping the
> coin, but when I try to do this 100 times I end up with it running through
> 100 times, but always the same result comes back. It will either be 100
> heads, or 100 tails. I have tried if statements and while loops and both
> seem to give me all or nothing. I am just looking for a hint at the
> direction to look of adjust to get the code below working not really the
> solution. Thanks in advanced for any tips.
>
> #!/usr/bin/python
> import random
>
> coin = random.randrange(2)
>
> count = 0
> head_count = 0
> tail_count = 0
>
> while (count != 100):
> if coin == 0:
> print "You got Heads!"
> head_count = head_count + 1
> count = count + 1
> else:
> print "You got Tails!"
> tail_count = tail_count + 1
> count = count + 1
>
> print "Out of", count, "you flipped", head_count, "heads and ", tail_count,
> "tails"
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] raw string - solution to open_new() problem

2005-08-08 Thread Alan G
> webbrowser.open_new(r"file://C:\__Library\folders\02394 Yale Style 
> Manual\02394 Yale_Style_Manual.htm")
>
> does.
>
> Thank you Ewald, for triggering the solution in my mind!
>
> Now, if anyone can explain why webbrowser.open_new() does the 
> character  substitution thing it was doing (and thus becoming unable 
> to locate the  file in question), I'm eager to hear it.

It's not the function that does it, it's Python itself.

If you just try using print for the two values(with and without 'r') 
you will see
the same effect. It's standard Python string handling.

Alan G. 

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


Re: [Tutor] use of webbrowser.open_new()

2005-08-08 Thread Danny Yoo


> > http://www.faqs.org/rfcs/rfc1738.html
> >
> > shows the syntax of file URLs.
>
> Man, that Berners-Lee can sure write plain English, can he not? I didn't
> find that reference much use at all, in truth.


Hi Tom,


[Note: when you're responding to a message on Python-tutor, please make
sure to CC to the mailing list too.]


It's meant to be a bit terse.  The second on file urls isn't too bad
though.  Here, let's take a closer look at it:

"""
   The file URL scheme is used to designate files accessible on a
   particular host computer. This scheme, unlike most other URL schemes,
   does not designate a resource that is universally accessible over the
   Internet.

   A file URL takes the form:

   file:///

   where  is the fully qualified domain name of the system on
   which the  is accessible, and  is a hierarchical
   directory path of the form //.../.

   As a special case,  can be the string "localhost" or the empty
   string; this is interpreted as `the machine from which the URL is
   being interpreted'.
"""


According to the file URL spec, you need to use forward slashes, not back
slashes, when defining the subdirectory path.  Your web browser might be
nice enough to try to account for backslashes, but it's not standard.
That's why the reference is relevant: it tells how to write out file urls
so that any web browser that follows the standard will do the right thing.




> webbrowser.open_new("file://C:\www\02394-Yale_Style_Manual.htm")

Here's a possible correction:

   webbrowser.open_new("file:///C:/www/02394-Yale_Style_Manual.htm")


We need three forward slashes in front of 'file:' because, in the file
URL:

   file:///

we're leaving the host part empty to say that we're looking at a local
file (last paragraph of the quoted section above), and forward slashes
instead of backslashes, since that's what the spec says.  *grin*



But even more importantly: backslashes in string literals are special.
You may have seen something like this before:

##
>>> print "hello\tworld\nthis is a\ntest"
hello   world
this is a
test
##


That the backslash starts an "escape character".  "\t" stands for the tab
character, and "\n" stands for the newline character.  This is relevant to
your problem because "\0239" stands for another escaped character.  For
more details on these escape sequences, see:

http://www.python.org/doc/ref/strings.html


Quickest way to fix this: don't use backslashes!  *grin*

Use forward slashes instead.  Backslashes in string literals are special,
and we have to take special care for them.  If we do want to put a literal
backslash in our string, we have to double the backslashes up:

##
>>> s = "hello\\world"
>>> print s
hello\world
##

but it's often just simpler just to use forward slashes for paths instead.


Good luck!

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


Re: [Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Danny Yoo


On Mon, 8 Aug 2005, Jan Eden wrote:

> Is there a recommended way to receive the results of an SQL query in the
> form I need? Or do I have to create a dictionary of fieldname tuples
> which can be zipped with the query result tuple?


Hi Jan,

MySQLdb supports the concept of customized cursor types.  They have a
particular cursor class that returns dictionary objects:

##
>>> import MySQLdb
>>> import MySQLdb.cursors
>>> MySQLdb.cursors.DictCursor

##


When we construct a connection object, we can tell MySQL to construct
those kind of custom cursors by default:

##
>>> conn = MySQLdb.connect(db='test_adb',
...cursorclass=MySQLdb.cursors.DictCursor)
>>> cursor = conn.cursor()
>>> cursor.execute("""select name, start_coordinate,
...end_coordinate
...   from BAC""")
1624L
>>>
>>> cursor.fetchone()
{'name': 'F10A5', 'end_coordinate': 28462975L, 'start_coordinate':
28333429L}
>>> cursor.fetchone()
{'name': 'T12M4', 'end_coordinate': 3002250L, 'start_coordinate':
2942990L}
>>> cursor.fetchone()
{'name': 'T12I7', 'end_coordinate': 24869607L, 'start_coordinate':
24834300L}
##


Good luck!

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


Re: [Tutor] deck dealing program

2005-08-08 Thread luke
Just offering my take on the problem.
hope it helps someone.
- Original Message -
From: <[EMAIL PROTECTED]>
To: 
Sent: Monday, August 08, 2005 2:02 AM
Subject: Re: [Tutor] deck dealing program


> Are you:
>   a.) Having trouble with the code and looking for help?
>   b.) Looking for suggestions on how to improve the code?
>   c.) Offering the code as a demo for Nathan et al.?
>
> I was just doing stuff along the same lines and was having fun seeing the
> different approaches to the same problem.
>
> --Todd
>
> On Monday 08 August 2005 02:38 am, luke wrote:
> > from random import randint
> >
> > def identify_card(n):
> > cardname = ""
> > royals = ["Jack","Queen","King","Ace"]
> > temp = n % 13
> > if temp > 8:
> > cardname += royals[temp-9]
> > else:
> > cardname += str(temp+2)
> > cardname += " of "
> >
> > suits = ["Spades","Hearts","Diamonds","Clubs"]
> > cardname += suits[n/13]
> > return cardname
> >
> > def main():
> > deck = range(52)
> > cards = []
> > while 1:
> > x = raw_input("how many cards do you want? ")
> > try:
> > x = int(x)
> > except ValueError:
> > print "Invalid value exiting for I have no error code.
Please
> > use an int next time." raise SystemExit
> > if x <= 52 and x >= 0:
> > y = 0
> > while y < x:
> >
> > cards.append(identify_card(deck.pop(randint(0,len(deck)-1 y += 1
> > break
> > print cards
> > if __name__ == "__main__":
> > main()
> >
> > #Luke
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Curses example on Linux?

2005-08-08 Thread Danny Yoo


On Mon, 8 Aug 2005, Hossein Movahhedian wrote:

>I have copied the following example from "Learning to Program by Alan
>  Gauld (section: Event Driven Programming)". To run it on Linux
>  (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt'
>  with 'curses.stdscr'.


Hi Hossein,


According to:

http://www.amk.ca/python/howto/curses/


Alan probably meant to say to replace:

##
import msvcrt
##

with:

##
import curses
msvcrt = curses.initscr()
##

as a quick hack to replace 'msvcrt' with something that works on Linux.


It sounded that you wanted to look at other examples of curses
programming?  A long time ago, I wrote a quick-and-dirty demo program that
uses curses here:

http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py


Good luck to you!

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


Re: [Tutor] Using urllib to retrieve info

2005-08-08 Thread Alan G
> It runs fine but the file saved to disk is the
> information at : 'http://support.mywork.co.uk'
> not
> 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897";'

Could there be cookies involved?

Just a thought,

Alan G. 

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


Re: [Tutor] Shut up and deal!

2005-08-08 Thread Danny Yoo


On Mon, 8 Aug 2005, Greg Lindstrom wrote:

> I found the conversation of dealing cards interesting, so I took a few
> minutes (about 20 while I waited for a production run to finish) and
> came up with the following Dealer class.

[text cut]

> What type of Pythonic changes would make this? What features would be
> nice?


Hi Greg,

For your program, it can make sense to treat the Cards themselves as a
class, rather than have them be just a string representation of a card.
Something like this:

##
class Card:
def __init__(self, suit, rank):
self.suit, self.rank = suit, rank
##

might work because then we can treat Cards as a separate data type.

One advantage is that we can then later extract the rank or suit out of
the card without having to do any string manipulation.  If we still want
to make it easy to get a string representation of these cards, we can add
an __str__() method to the Card class definition.

There's often a temptation to make everything a string because we're
comfortable with them, but sometimes that representation choice makes
things hard on ourselves when we're doing more than pure string
manipulation.

Hope this helps!

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


Re: [Tutor] What's the invalid syntax? Code supplied

2005-08-08 Thread Alan G
Nathan,

> I'm no longer going to use this method. I thought up a more easier 
> idea for dealing cards. I was going to share it, but with all this 
> time and effort pointing out things that I should know, instead of 
> helping me, I don't think I will, because it will probably be ripped 
> to shreds by you, and dash my idea before it even takes off.

Now I've had some sleep I'll try to be a little kinder.

I was not trying to 'rip you to shreds' but to help you.

But you are not helping us to help you by posting code that is full of
basic syntax errors. Try to fix those yourself and if you get stuck 
tell
us what the problem is and include the error text. Python does very 
well
at printing useful error messages, without which we are left having to
read your code line by line. This means we don't know whether you are
looking for a new approach, help with the syntax, or just general
comments.

Many of the mistakes you are making are covered in the various 
tutorials
that are on the web, some time spent reading those will avoid many of
the problems you are encountering. And reading documentation is an
essential skill for any programmer to learn. While the mailing list
is here to help newbies to Python and programming we are all 
volunteers
doing this in our own time. We are happy to help folks who are stuck, 
we
just ask for some help in that you give us as much specific 
information
about the help you need as possible. A subject line saying 'it doesn't 
work'
and a screen full of code is not enough.

> I wanted help, and you critised me,
> I wanted aid, and you refused,
> So I will do it myself!

No-one has refused you, but doing it by yourself is a big part of 
learning
and no bad thing. You have made some progress since you started 
posting to
the list, but you could progress faster by paying more attention to 
the basics.
The list is best used for the times when you are unable to make any 
further
progress by yourself.

As I said in my post yesterday we are trying to help you to help 
yourself.

I'm sorry if my words sounded harsh but they were borne out of seeing
a posting with no clue as to the problem but full of basic syntax 
errors.
And maybe it could have been expressed more subtly but having returned
from 3 long days I was not in the mood for sweet talking! :-(

Sorry if it offended, it was not meant so to do.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

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


Re: [Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Jan Eden
Hi Danny,

Danny Yoo wrote on 08.08.2005:

>On Mon, 8 Aug 2005, Jan Eden wrote:
>
>>Is there a recommended way to receive the results of an SQL query
>>in the form I need? Or do I have to create a dictionary of
>>fieldname tuples which can be zipped with the query result tuple?
>
>
>Hi Jan,
>
>MySQLdb supports the concept of customized cursor types.  They have
>a particular cursor class that returns dictionary objects:

Great! I found the pydoc for MySQLdb a bit confusing and would probably have 
taken quite a while to figure that out - thanks a lot.

- Jan
--  
Any technology which is distinguishable from magic is insufficiently advanced.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IP Address from Python module?

2005-08-08 Thread Joseph Quigley




Danny Yoo wrote:

  Hi Joe,

That actually sounds right in a sense.  Any internet address with
'192.168.x.x' is a "local" IP address, and is commonly allocated to folks
on an internal network.  For the really dull details about this, see RFC
1918 on "Private Address Space":

http://www.faqs.org/rfcs/rfc1918.html

So anything with 192.168.x.x is a private, internal address.  In the
context of the Internet, it's sorta useless, since it's not an address
that one can use to connect to an external machine outside of the local
area network.

In fact, Brian Hammon's comment in:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890

does mention that if you're behind a router, then the router itself sets
up a small private network, which may explain why you may be seeing
'192.168.x.x' as an address.

The second comment on the cookbook page shows an alternative technique
that should be more robust: use http://checkip.dyndns.org.



  
  
My internet IP should be IPv6 and I don't think it changes...

  
  
Are you sure about that?  IPv6 has not been widely deployed yet; most
folks still connect to the internet through the IPv4 protocol.

On the off-chance that you ARE on IPv6, see the getaddrinfo() function,
which should accomodate:

http://www.python.org/doc/lib/module-socket.html#l2h-2592

For example:

##
  
  

  
import socket
socket.getaddrinfo('hkn.eecs.berkeley.edu', 80)

  

  
  [(2, 1, 6, '', ('128.32.47.228', 80)),
 (2, 2, 17, '', ('128.32.47.228', 80))]
##


Good luck to you!


  

Thank you. And thank you for the links. Well I remember something on a
game I played and it had a IPv6 address (refering to my computer while
o nthe internet).. of course I bought my computer parts in October 2004
so there could be a good chance that I do not have IPv6... either way,
thanks. :-)

Oh and I don't have a router... just a good old-fashioned  CAT5 hub.

Joe


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


Re: [Tutor] while loops

2005-08-08 Thread Will Harris
Thanks for the help guys.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using urllib to retrieve info

2005-08-08 Thread Liam Clarke-Hutchinson
Hi all, 

David, are you able to send us a screen shot of what you're trying to get? 
>From your desired link I just get a bunch of ads with another ad telling me
it's for sale. 
When I open http://support.mywork.co.uk it looks exactly the same as 
http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objec
tid=21897

So yah, are there cookies, it looks like the site lost it's domain to me.

You may also find that urllib's User Agent setting causes some sites to flat
out spit the dummy.
Try google.com with urllib without changing the user agent, google gets all
huffy when rival bots attempt to spider it. 

I believe you can change the User-Agent using urllib, 
so you can easily masquerade as Internet Explorer or a Mozilla browser. 

>From http://docs.python.org/lib/module-urllib.html

"""
By default, the URLopener class sends a User-Agent: header of "urllib/VVV",
where VVV is the urllib version number. 
Applications can define their own User-Agent: header by subclassing
URLopener or FancyURLopener and 
setting the class attribute version to an appropriate string value in the
subclass definition.
"""

That's another caveat when using urllib. 

But yeah, digression aside, short answer is, I think your specified resource
is dead, and a url-camper has
taken all urls for that site and redirected them to a pop-up fest. 

Regards, 


Liam Clarke-Hutchinson

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Alan G
Sent: Tuesday, 9 August 2005 6:33 a.m.
To: David Holland; tutor python
Subject: Re: [Tutor] Using urllib to retrieve info


> It runs fine but the file saved to disk is the
> information at : 'http://support.mywork.co.uk'
> not 
> 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=2039
> 7&objectid=21897"'

Could there be cookies involved?

Just a thought,

Alan G. 

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

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] NotebookSizer is no longer needed

2005-08-08 Thread _ Dan _
Hi...
Well, I'm working on Gui programs with wxglade. On MS
Windows I'm getting the following message:
"DeprecationWarning: NotebookSizer is no longer
needed"
No message on Linux... and, if I remove the notebook
sizer, then I cannot put any notebook at all, so I'm
kind of lost in here...
Anybody knows about this? :(

My tree is like:

Frame_1
   Sizer_1
  Notebook_1
 Note_book_pane_1
 Note_book_pane_2

So the Sizer_1 would be the "NotebookSizer". If I
remove it, then I can't place a notebook, at least in
wxglade. Anyhow, I know very little about wxpython...
>From Chile, 
Daniel.



__ 
Renovamos el Correo Yahoo! 
Nuevos servicios, más seguridad 
http://correo.yahoo.es
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] problem with Python Tutorial

2005-08-08 Thread Dick Moores
Quoting from "6.2 Standard Modules", of the Python Tutorial 
():

==
One particular module deserves some attention: sys, which is built into 
every Python interpreter. The variables sys.ps1 and sys.ps2 define the 
strings used as primary and secondary prompts:


 >>> import sys
 >>> sys.ps1
'>>> '
 >>> sys.ps2
'... '
 >>> sys.ps1 = 'C> '
C> print 'Yuck!'
Yuck!
C>

These two variables are only defined if the interpreter is in interactive 
mode.
end of quote===

I tried this with IDLE:

 >>> import sys
 >>> sys.ps1

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 sys.ps1
AttributeError: 'module' object has no attribute 'ps1'
 >>> sys.ps2

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 sys.ps2
AttributeError: 'module' object has no attribute 'ps2'

What's wrong?

Thanks,

Dick Moores



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


[Tutor] help

2005-08-08 Thread Dan Deternova
i am making a simple script to get the hang of Tkinter. i want to use the input of the user from a Entry and calcuate the area. i have tryied many way... as you can see in my script.   the Entry is under def area():  and the output i want is under def cal():  ... please help me fix my code and explain to me what you did.. thanks in advance.
[EMAIL PROTECTED]
#program made and maintained by Dan Deternova
#start of program

from Tkinter import *   
# tells computer we are using Tkinter modual
from tkMessageBox import *
def cal():
win4 = Toplevel
print 'area = ', 'w'*'h'
def notyet():
showerror('not yet avalable')

win = Tk()  
# makes windows and has value for Tk
def makemenu(Tk):
top = Menu(win)
win.config(menu=top)

file = Menu(top)
file.add_command(label='save your name', command=newwin, underline=0)
file.add_command(label='quit', command=win.destroy, underline=0)
file.add_command(label='quit all', command=win.quit, underline=0)
top.add_cascade(label='file', menu=file, underline=0)
edit = Menu(top, tearoff=0)
edit.add_command(label='copy', command=notyet, underline=0)
edit.add_command(label='paste', command=notyet, underline=0)
edit.add_command(label='quit', command=win.destroy, underline=0)
top.add_cascade(label='edit', menu=edit, underline=0)


def newwin():   
# callback to define button newwin.
win2 = Toplevel()   
# makes new window when button is pressed. named win2
widget = Label(win2, text='your name here').pack()  
# line 'type your name here' is printed on top of entry
name = StringVar()
widget = Entry(win2, textvariable=name).pack()  
# makes entry in new window at the top.
widget = Label(win2, text='age here').pack()
# prints the line 'age here'
age = StringVar()
widget = Entry(win2, textvariable=age).pack()   
# makes entry
widget = Label(win2, text='type your address here').pack()
address = StringVar()
widget = Entry(win2, textvariable=address).pack()
def save():
 f=file('fname','a')
 f.write(name.get()+'\n')
 f.write(age.get()+'\n')
 f.write(address.get()+'\n')

widget = Button(win2, text='save', command=save).pack(side=LEFT)
widget = Button(win2, text='quit', command=win2.destroy).pack(side=RIGHT)
def area():
win3 = Toplevel()
widget = Label(win3, text='type hieght here: ').pack()
h = StringVar()
widget = Entry(win3, textvariable=h).pack()
widget = Label(win3, text='type width here:  ').pack()
w = StringVar()
widget = Entry(win3, textvariable=w).pack()
widget = Button(win3, text=' calculate ', command=cal).pack(side=BOTTOM, 
expand=YES, fill=BOTH)
fontentry = ('times', 20, 'bold')   
# (font, size, style) defonision for fontentry. will be used later 
on in the program
widget = Entry(win, text='type here')   
# makes entry point in 'win'
makemenu(win)
widget.config(font=fontentry)   
# makes the font of entry equal to 'fontentry'
widget.config(bg='black', fg='yellow')  
# makes the background (bg) black and the forground (text) yellow
widget.pack(side=TOP, expand=YES, fill=BOTH)
# 'packs' the entry on top of win and expands and fill the Y axes
widget = Button(win, text="your name", command=newwin).pack(side=LEFT, 
expand=YES, fill=BOTH)# creates button that says 'your name'. see newwin 
callback for output.
widget = Button(win, text='quit all', command=win.quit).pack(side=BOTTOM, 
expand=YES, fill=BOTH)
widget = Button(win, text='quit', command=win.destroy).pack(side=RIGHT, 
expand=YES, fill=BOTH)
widget = Button(win, text='area', command=area).pack(side=LEFT, expand=YES, 
fill=BOTH)
win.title('my program')

#end of program

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


Re: [Tutor] problem with Python Tutorial

2005-08-08 Thread Danny Yoo
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  sys.ps2
> AttributeError: 'module' object has no attribute 'ps2'
>
> What's wrong?


IDLE doesn't use sys.ps2.  See the thread starting at:

http://mail.python.org/pipermail/idle-dev/2002-February/000862.html

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


Re: [Tutor] NotebookSizer is no longer needed

2005-08-08 Thread _ Dan _

There is a good chance I got it all wrong...



__ 
Renovamos el Correo Yahoo! 
Nuevos servicios, más seguridad 
http://correo.yahoo.es--- Begin Message ---
Hi...
Well, I'm working on Gui programs with wxglade. On MS
Windows I'm getting the following message:
"DeprecationWarning: NotebookSizer is no longer
needed"
No message on Linux... and, if I remove the notebook
sizer, then I cannot put any notebook at all, so I'm
kind of lost in here...
Anybody knows about this? :(

My tree is like:

Frame_1
   Sizer_1
  Notebook_1
 Note_book_pane_1
 Note_book_pane_2

So the Sizer_1 would be the "NotebookSizer". If I
remove it, then I can't place a notebook, at least in
wxglade. Anyhow, I know very little about wxpython...
>From Chile, 
Daniel.



__ 
Renovamos el Correo Yahoo! 
Nuevos servicios, más seguridad 
http://correo.yahoo.es
--- End Message ---
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with Python Tutorial

2005-08-08 Thread Dick Moores
Danny Yoo wrote at 16:57 8/8/2005:
> > Traceback (most recent call last):
> >File "", line 1, in -toplevel-
> >  sys.ps2
> > AttributeError: 'module' object has no attribute 'ps2'
> >
> > What's wrong?
>
>
>IDLE doesn't use sys.ps2.  See the thread starting at:
>
> http://mail.python.org/pipermail/idle-dev/2002-February/000862.html


Thanks, Danny. Should that info be added to the tutorial?

Dick 

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


Re: [Tutor] problem with Python Tutorial

2005-08-08 Thread Danny Yoo


On Mon, 8 Aug 2005, Dick Moores wrote:

> Danny Yoo wrote at 16:57 8/8/2005:
> > > Traceback (most recent call last):
> > >File "", line 1, in -toplevel-
> > >  sys.ps2
> > > AttributeError: 'module' object has no attribute 'ps2'
> > >
> > > What's wrong?
> >
> >
> >IDLE doesn't use sys.ps2.  See the thread starting at:
> >
> > http://mail.python.org/pipermail/idle-dev/2002-February/000862.html
>
> Thanks, Danny. Should that info be added to the tutorial?


It can't hurt (much) to send a ping off to the documentation folks and see
if they can add a note about it in the tutorial.  Send a message off to
the [EMAIL PROTECTED] folks about it.

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


[Tutor] function won't import from module

2005-08-08 Thread Dick Moores
I have a bunch of functions I've collected in one script, "mycalc.py", 
which I use as a module, "mycalc". The last one I wrote, cmpSeq() is as 
follows:

===begin code==
def cmpSeq(seq1, seq2):
 """
 find first index at which two sequences differ
 """
 if seq1 == seq2:
 print "Sequences are identical, and of length %d" % len(seq1)
 return None
 if len(seq1) >= len(seq2):
 shorterOrEqualSequence = seq2
 else:
 shorterOrEqualSequence = seq1

 for index in range(len(shorterOrEqualSequence)):
 if seq1[index] != seq2[index]:
 print "sequences first differ at index", index
 print "seq1[%d] = %s" % (index, seq1[index])
 print "seq2[%d] = %s" % (index, seq2[index])
 break

 if index == len(shorterOrEqualSequence)-1:
 print "sequences are identical thru end of shorter sequence at 
index", index

 print "len(seq1) =", len(seq1)
 print "len(seq2) =", len(seq2)
end code for cmpSeq()=

In a script, cmpSeq() works fine. For example followed by

a = "qwertys"
b = "qxerty"
cmpSeq(a,b)

The output is:

sequences first differ at index 1
seq1[1] = w
seq2[1] = x
len(seq1) = 7
len(seq2) = 6



cmpSeq() is now copy-pasted into mycalc.py, but is not useable there:

#testof_cmpSeq.py
import mycalc
a = "qwerty"
b = "qxerty"
mycalc.cmpSeq(a,b)

which produces:

Traceback (most recent call last):
   File "C:\Python24\MyScripts\testof_cmpSeq.py", line 1, in -toplevel-
 from mycalc import cmpSeq
ImportError: cannot import name cmpSeq

However, other functions in mycalc work fine. For example:

#testof_print_hms
import mycalc

seconds = 87658
mycalc.print_hms(seconds)

This outputs   24 hours, 20 minutes, 58 seconds



That may have been a bit long-winded; if so, I apologize.

But would someone please point out why cmpSeq() can't be imported from 
mycalc?

Thanks,

Dick Moores










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


Re: [Tutor] function won't import from module

2005-08-08 Thread Javier Ruere
Dick Moores wrote:
> I have a bunch of functions I've collected in one script, "mycalc.py", 
> which I use as a module, "mycalc". The last one I wrote, cmpSeq() is as 
> follows:
>
[code]
>
> In a script, cmpSeq() works fine. For example followed by
>
[example]
>
> The output is:
> 
[output]
> 
> cmpSeq() is now copy-pasted into mycalc.py, but is not useable there:
> 
[example]
> 
> which produces:
> 
[Traceback]
>
> However, other functions in mycalc work fine. For example:
> 
[example]
> 
> That may have been a bit long-winded; if so, I apologize.

  Not at all! :)
  I couldn't reproduce the error. The problem is not in the given code then. 
Use PyChecker or PyLint to aid you find the problem.

  Other comments:

Instead of:

 for index in range(len(shorterOrEqualSequence)):
 if seq1[index] != seq2[index]:
 prints...
 break

 if index == len(shorterOrEqualSequence)-1:
 print "sequences are identical thru end of shorter sequence at index", 
index

this could be used:

 for index in range(len(shorterOrEqualSequence)):
 if seq1[index] != seq2[index]:
 prints...
 break
 else:
 print "sequences are identical thru end of shorter sequence at index", 
index

And instead of:

 if len(seq1) >= len(seq2):
 shorterOrEqualSequence = seq2
 else:
 shorterOrEqualSequence = seq1

 for index in range(len(shorterOrEqualSequence)):
 etc.

this could be used:

 for index in xrange(min(len(seq1), len(seq2))):
 etc.

The main loop, I would write it like this:

 from itertools import izip, count

 def cmpSeq(seq1, seq2):
  """
  find first index at which two sequences differ
  """
  if seq1 == seq2:
  print "Sequences are identical, and of length %d" % len(seq1)
  return None

  for i, ca, cb in izip(count(), seq1, seq2):
  if ca != cb:
  print "sequences first differ at index", index
  print "seq1[%d] = %s" % (index, seq1[index])
  print "seq2[%d] = %s" % (index, seq2[index])
  break
  else:
  print "sequences are identical thru end of shorter sequence at 
index", i


Javier

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