Re: [Tutor] Solve wave equation

2012-02-24 Thread Jose Amoreira
On Thursday, February 23, 2012 12:57:39 PM David Craig wrote:
> Hi,
> I am trying to write some code that will solve the 2D wave equation by
> the finite difference method, but it just returns an array full of zeros
> and NaN's. Not sure where I am going wrong, the code is attached so if
> could someone point me in the right direction I'd appreciate this.
> Thanks
> D

Let me add my 2 cents to Steven's suggestions.

The main cicle of your program can be reorganized, pulling out all constant 
calculations. Where you write
>for t in range(2,nsteps-1):
>
>
>for z in range(1,nz-1):
>
>for x in range(2,nx-1):
>
>p[xs,zs,t] = s[t]
>
>k = (c*dt/h)**2
>
>p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + [...]

I'd write

k = (c*dt/h)**2
for t in range(2,nsteps-1):
p[xs,zs,t] = s[t]
for z in range(1,nz-1):
for x in range(2,nx-1):
p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + [...]

Like that you don't have to compute the value of k (wich is constant) for each 
cell in your mesh and for every time slice. I didn't quite understand the way 
you integrate the source in the calculation, but if it works the way you do 
it, it should also work putting it out of the x and z loops; like that, you 
just have to compute it once for each time slice.

Also, whenever possible, try to implement the iterations (for loops) over 
array elements as whole array operations, wich are way faster then python for 
loops. For instance, the laplacian of the wave function,

>  k*(p[x+1,z,t-1]-4*p[x,z,t-1]+p[x-1,z,t-1]+p[x,z+1,t-1]+p[x,z-1,t-1])

can be computed at once (without for loops) with something like (haven't tryed 
it, take care, read the docs)

>k*(roll(p[:,:,t-1],-1,axis=1) - 4*p[:,:,t-1] + roll(p[:,:,t-1],1,axis=1) +
roll(p[:,:,t-1],-1,axis=0) + roll(p[:,:,t-1],1,axis=0))

(mind the linebreak). This expression returns an array with the dimensions of 
your pressure array p. It may have to be tweaked a bit because of boundary 
behaviour of the roll function.
roll() is a numpy function (must be imported from numpy) that shifts the array 
elements. See 
http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html
Some examples:

In [1]: from numpy import *

In [2]: m=array([[11,12,13],[21,22,23],[31,32,33]])

In [3]: print m
[[11 12 13]
 [21 22 23]
 [31 32 33]]

In [4]: roll(m,-1,axis=1)
Out[4]: 
array([[12, 13, 11],
   [22, 23, 21],
   [32, 33, 31]])

In [5]: roll(m,1,axis=0)
Out[5]: 
array([[31, 32, 33],
   [11, 12, 13],
   [21, 22, 23]])

Finally, about the plot, I find the matplotlib contour function too slow (it's 
not trivial to compute the contour lines) for animations. I prefer a method 
that directly maps values into colors. Someone in this list suggested pygame's 
surfarray methods, and that's what I've been using.
I hope this helps. Cheers,
Ze
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Suggestions for a good intro OO & Python

2012-02-24 Thread Sivaram Neelakantan

Can someone point me to a good intro on OO in Python?  If it does OO
basics too, even better, assuming no prior knowledge of Object
Orientation. 

 sivaram
 -- 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Attribute error message received on Card Game program

2012-02-24 Thread SKHUMBUZO ZIKHALI


Hi 

I am trying to run the following program from Guide to Programming with Python 
by Micheal Dawson:
 

class Card(object):
    RANK = ["A","2","3","4","5","6","7"
    "8","9","K","Q","J"]
    SUIT = ["s","d","h","c"]
    def __init__(self,rank, suit):
    self.rank = rank
    self.suit = suit
    def __str__(self):
    rep = self.rank + self.suit
    return rep
 
class Hand(object):
    def __init__(self):
    self.cards = []
    def __str__(self):
    if self.cards:
    rep = ''
    for card in self.card:
    rep += str(Card)+''  
    else:
    rep = ""
    return rep
    def clear(self):
    self.cards =[]
    def add(self, card):
    self.cards.append(card)
    def give(self, card, other_hand):
    self.cards.remove(card)
    other_hand.add(card)

# Main

card1 = Card(rank = "A", suit ="c")
print 'Printing a Card object'
print card1
card2 = Card(rank = "2", suit ="c")
card3 = Card(rank = "3", suit ="c")
card4 = Card(rank = "4", suit ="c")
card5 = Card(rank = "5", suit ="c")
print card2
print card3
print card4
print card5
my_hand = Hand()
print '\nPrinting my hand before I add my card:'
print my_hand
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print '\nPrinting my hand after adding 5 cards:'
print my_hand
your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print '\nGave the first two cards from my hand to your hand.'
print 'Your hand:'
print your_hand
print 'My hand:'
my_hand
my_hand.clear()
print '\nMy hand after clearing it:'
raw_input('\n\nPress the enter key to exist.')

However, I can partly run it for eventually receive attribute error message. 
Printing response is as follows: 

2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>  RESTART 
>>> 
Printing a Card object
Ac
2c
3c
4c
5c
Printing my hand before I add my card:

Printing my hand after adding 5 cards:
Traceback (most recent call last):
  File "C:/Python27/Card Game.py", line 69, in 
    print my_hand
  File "C:/Python27/Card Game.py", line 25, in __str__
    for card in self.card:
AttributeError: 'Hand' object has no attribute 'card'
>>> 

Would you please help me as to where I got it wrong with this program and 
lastly inform how how does Hand object gets linked or connected with Card 
object? 

With thanks 

Sikhumbuzo    
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] problem editing modules and defs

2012-02-24 Thread David Craig

Hi,
I am new to python and have made a couple of definitions. I imported 
them and they worked ok. I they worked except for one which gave me the 
error "NameError: global name 'np' is not defined". I then edited my 
script for the def to include "import numpy as np" saved it and imported 
the def again. However, it still gives me the same error. I know I have 
to be doing something basic wrong but cant figure it out, anyone know 
what I am doing wrong. The def is below.

thanks
D

import numpy as np

def find_nearest(array,value):
idx=(np.abs(array-value)).argmin()
return array[idx]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem editing modules and defs

2012-02-24 Thread Evert Rol
  Hi David,

> Hi,
> I am new to python and have made a couple of definitions. I imported them and 
> they worked ok. I they worked except for one which gave me the error 
> "NameError: global name 'np' is not defined". I then edited my script for the 
> def to include "import numpy as np" saved it and imported the def again. 
> However, it still gives me the same error. I know I have to be doing 
> something basic wrong but cant figure it out, anyone know what I am doing 
> wrong. The def is below.
> thanks

Minor thing first: in Python terminology, most of the time your 'definitions' 
are simply called functions, although you're correct that "def" refers to 
definition. But thatt's more about where the function is defined, in contrast 
to where in the code it is called (or perhaps even declared, though I don't 
think that applies to Python).


When you say "I imported the def again", it sounds like you're working on the 
Python interpreter, and doing
>>> import myscript
or similar.
If that's how you run things, you would have to use the reload() function to 
reload the new function definition, which has your correction.

However, you also talk about 'my script'. A script is something I would run 
from the shell command line, like
$> python myscript.py

If you do things that way, you would always be ensured that python uses the 
latest edits in your script.
It does mean that any command you would normally type into the Python 
interpreter, you would now have to enter in the script. And while the 
interpreter always shows the evaluation result of the last command entered, a 
script would require a print for that. Compare:
>>> a=1
>>> a
1

versus (inside a script):
a = 1
a  # this doesn't show anything
print a  # this does

Perhaps this is too basic, but I have to guess a bit what you are doing from 
your text.

A few tips to get more practical help:
- Python normally shows a stack trace when there is an error. It is good to 
copy-paste the whole thing in your emails. Just typing the last bit often 
doesn't help.
- Copy-paste (again, don't type) whatever you're doing in the Python 
interpreter, if that's what you are using. So we can how you do things 
(examples are clearer than descriptions). If needs be, intersperse with 
comments.
Compare eg:
>>> import myscript
NameError: global name 'np' is not defined".
>>> # editing myscript.py
>>> import myscript
NameError: global name 'np' is not defined".

And we can immediately see you don't reload() the script.

Hope this gets you further.

Have fun,

  Evert



> D
> 
> import numpy as np
> 
> def find_nearest(array,value):
>idx=(np.abs(array-value)).argmin()
>return array[idx]
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] problem editing modules and defs

2012-02-24 Thread David Craig

Hi,
I am new to python and have made a couple of definitions. I imported 
them and they worked ok except for one which gave me the error 
"NameError: global name 'np' is not defined". I then edited my script 
for the def to include "import numpy as np" saved it and imported the 
def again. However, it still gives me the same error. I know I have to 
be doing something basic wrong but cant figure it out, anyone know what 
I am doing wrong. The def is below.

thanks
D

import numpy as np

def find_nearest(array,value):
idx=(np.abs(array-value)).argmin()
return array[idx]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Attribute error message received on Card Game program

2012-02-24 Thread bob gailer

On 2/24/2012 11:08 AM, SKHUMBUZO ZIKHALI wrote:

Hi
/*I am trying to run the following program from Guide to Programming 
with Python by Micheal Dawson:*/

/**/

class Card(object):
RANK = ["A","2","3","4","5","6","7"
"8","9","K","Q","J"]
SUIT = ["s","d","h","c"]
def __init__(self,rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep

class Hand(object):
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ''
for card in self.card:

Did you mean self.cards?

rep += str(Card)+''
else:
rep = ""
return rep
def clear(self):
self.cards =[]
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
# Main
card1 = Card(rank = "A", suit ="c")
print 'Printing a Card object'
print card1
card2 = Card(rank = "2", suit ="c")
card3 = Card(rank = "3", suit ="c")
card4 = Card(rank = "4", suit ="c")
card5 = Card(rank = "5", suit ="c")
print card2
print card3
print card4
print card5
my_hand = Hand()
print '\nPrinting my hand before I add my card:'
print my_hand
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print '\nPrinting my hand after adding 5 cards:'
print my_hand
your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print '\nGave the first two cards from my hand to your hand.'
print 'Your hand:'
print your_hand
print 'My hand:'
my_hand
my_hand.clear()
print '\nMy hand after clearing it:'
raw_input('\n\nPress the enter key to exist.')
/*However, I can partly run it for eventually receive attribute error 
message. Printing response is as follows:*/
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on 
win32

Type "copyright", "credits" or "license()" for more information.
>>>  RESTART 


>>>
Printing a Card object
Ac
2c
3c
4c
5c
Printing my hand before I add my card:

Printing my hand after adding 5 cards:
Traceback (most recent call last):
  File "C:/Python27/Card Game.py", line 69, in 
print my_hand
  File "C:/Python27/Card Game.py", line 25, in __str__
for card in self.card:
AttributeError: 'Hand' object has no attribute 'card'
>>>
/*Would you please help me as to where I got it wrong with this 
program and lastly inform how how does Hand object gets linked or 
connected with Card object? */

With thanks
Sikhumbuzo */
/*


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help writing functions

2012-02-24 Thread Wayne Werner



On Thu, 23 Feb 2012, Saad Javed wrote:


I am learning python and need guidance for
writing some code. I've written a simple
program (with pointers from people) that
parses an tv show xml feed and prints their
values in plain text after performing some
string operations.


Unless you're really interested in doing this fire the sake of the exercise you
should probably take a look at feedparser
 it's designed for parsing read and atom feeds.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Attribute error message received on Card Game program

2012-02-24 Thread Dave Angel

On 02/24/2012 11:34 AM, bob gailer wrote:

On 2/24/2012 11:08 AM, SKHUMBUZO ZIKHALI wrote:

Hi
/*I am trying to run the following program from Guide to Programming 
with Python by Micheal Dawson:*/

/**/

class Card(object):
RANK = ["A","2","3","4","5","6","7"
"8","9","K","Q","J"]
SUIT = ["s","d","h","c"]
def __init__(self,rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep

class Hand(object):
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ''
for card in self.card:

Did you mean self.cards?

rep += str(Card)+''
else:
rep = ""


Did you mean to return   rep   for both the if and else portion?  If so, 
this return statement should be unindented to line up with the else: line.



return rep
def clear(self):
self.cards =[]
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
# Main
card1 = Card(rank = "A", suit ="c")
print 'Printing a Card object'
print card1
card2 = Card(rank = "2", suit ="c")
card3 = Card(rank = "3", suit ="c")
card4 = Card(rank = "4", suit ="c")
card5 = Card(rank = "5", suit ="c")
print card2
print card3
print card4
print card5
my_hand = Hand()
print '\nPrinting my hand before I add my card:'
print my_hand
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print '\nPrinting my hand after adding 5 cards:'
print my_hand
your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print '\nGave the first two cards from my hand to your hand.'
print 'Your hand:'
print your_hand
print 'My hand:'
my_hand
my_hand.clear()
print '\nMy hand after clearing it:'
raw_input('\n\nPress the enter key to exist.')
/*However, I can partly run it for eventually receive attribute error 
message. Printing response is as follows:*/
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on 
win32

Type "copyright", "credits" or "license()" for more information.
>>>  RESTART 


>>>
Printing a Card object
Ac
2c
3c
4c
5c
Printing my hand before I add my card:

Printing my hand after adding 5 cards:
Traceback (most recent call last):
  File "C:/Python27/Card Game.py", line 69, in 
print my_hand
  File "C:/Python27/Card Game.py", line 25, in __str__
for card in self.card:
AttributeError: 'Hand' object has no attribute 'card'
>>>
/*Would you please help me as to where I got it wrong with this 
program and lastly inform how how does Hand object gets linked or 
connected with Card object? */

With thanks
Sikhumbuzo */
/*




--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem editing modules and defs

2012-02-24 Thread David Craig
Hi again, sorry if that wasnt clear. I am using the ipython interpreter 
to debug scripts. I have a function:-) saved as part of a module called 
daves_modules.py.


   import numpy as np
   def find_nearest(array,value):

idx=(np.abs(array-value)).argmin()
return array[idx], idx


If I run the module from the interpreter as follows,


   In [610]: %run daves_modules.py

   In [611]: a = find_nearest(pos_time, highTime)

   In [612]: a
   Out[612]: (20.009998091697867, 200)


it works fine. However, if I use the same function in a script like this,

   import numpy as np
   import pylab as py
   from daves_modules import dist, find_nearest
   .
   .
   .
   a = find_nearest(pos_time, highTime)


I get the following error,

   %run SNR_UFAN_UCRUI.py
   ---
   IndexErrorTraceback (most recent
   call last)

   /home/davcra/python_scripts/SNR_UFAN_UCRUI.py in ()
 88 b = find_nearest(pos_time, lowTime)
 89
   ---> 90 pos_noise =
   (np.sum(pos_signal[0:a[1]])+np.sum(pos_signal[b[1]:-1])) / (a[1] +
   (len(pos_signal)-b[1]))
 91 neg_noise =
   (np.sum(neg_signal[0:-a[1]])+np.sum(neg_signal[-b[1]:-1])) / (a[1] +
   (len(neg_signal)-b[1]))
 92

   IndexError: invalid index to scalar variable.
   WARNING: Failure executing file: 


If I then try to use the function in ipython again,

   In [614]: a = find_nearest(pos_time, highTime)

   In [615]: a
   Out[615]: 20.009998091697867


Note: the function originally only returned array[idx], so it seems to 
have reverted to this somehow.






On 02/24/2012 04:28 PM, Evert Rol wrote:

   Hi David,


Hi,
I am new to python and have made a couple of definitions. I imported them and they worked ok. I 
they worked except for one which gave me the error "NameError: global name 'np' is not 
defined". I then edited my script for the def to include "import numpy as np" saved 
it and imported the def again. However, it still gives me the same error. I know I have to be doing 
something basic wrong but cant figure it out, anyone know what I am doing wrong. The def is below.
thanks

Minor thing first: in Python terminology, most of the time your 'definitions' are simply 
called functions, although you're correct that "def" refers to definition. But 
thatt's more about where the function is defined, in contrast to where in the code it is 
called (or perhaps even declared, though I don't think that applies to Python).


When you say "I imported the def again", it sounds like you're working on the 
Python interpreter, and doing

import myscript

or similar.
If that's how you run things, you would have to use the reload() function to 
reload the new function definition, which has your correction.

However, you also talk about 'my script'. A script is something I would run 
from the shell command line, like
$>  python myscript.py

If you do things that way, you would always be ensured that python uses the 
latest edits in your script.
It does mean that any command you would normally type into the Python 
interpreter, you would now have to enter in the script. And while the 
interpreter always shows the evaluation result of the last command entered, a 
script would require a print for that. Compare:

a=1
a

1

versus (inside a script):
a = 1
a  # this doesn't show anything
print a  # this does

Perhaps this is too basic, but I have to guess a bit what you are doing from 
your text.

A few tips to get more practical help:
- Python normally shows a stack trace when there is an error. It is good to 
copy-paste the whole thing in your emails. Just typing the last bit often 
doesn't help.
- Copy-paste (again, don't type) whatever you're doing in the Python 
interpreter, if that's what you are using. So we can how you do things 
(examples are clearer than descriptions). If needs be, intersperse with 
comments.
Compare eg:

import myscript

NameError: global name 'np' is not defined".

# editing myscript.py
import myscript

NameError: global name 'np' is not defined".

And we can immediately see you don't reload() the script.

Hope this gets you further.

Have fun,

   Evert




D

import numpy as np

def find_nearest(array,value):
idx=(np.abs(array-value)).argmin()
return array[idx]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem editing modules and defs

2012-02-24 Thread Dave Angel

On 02/24/2012 11:11 AM, David Craig wrote:

Hi,
I am new to python and have made a couple of definitions. I imported 
them and they worked ok. I they worked except for one which gave me 
the error "NameError: global name 'np' is not defined". I then edited 
my script for the def to include "import numpy as np" saved it and 
imported the def again. However, it still gives me the same error. I 
know I have to be doing something basic wrong but cant figure it out, 
anyone know what I am doing wrong. The def is below.

thanks
D

import numpy as np

def find_nearest(array,value):
idx=(np.abs(array-value)).argmin()
return array[idx]


Evert's response was correct.  But let me put it simpler.  When (from a 
debugger) you import a MODULE a second time, it does essentially 
nothing.  It notices that it's already there, and doesn't waste time 
reloading it.   After all modules don't change during a program run.


There is a reload() function that theoretically works.  But it has 
enough limitations that I've never even bothered.  If you're going to 
change an imported source file, exit the interpreter and start over.  Or 
do what I do, and always run the SCRIPT from a command line, or from an IDE.


A point on terminology.  When you run a script, it's called a SCRIPT.  
If you import the same file, it's called a MODULE.  The two have 
slightly different behaviors.


--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem editing modules and defs

2012-02-24 Thread Walter Prins
Hi Dave,

On 24 February 2012 16:29, David Craig  wrote:
> Hi,
> I am new to python and have made a couple of definitions. I imported them
> and they worked ok except for one which gave me the error "NameError: global
> name 'np' is not defined". I then edited my script for the def to include
> "import numpy as np" saved it and imported the def again. However, it still
> gives me the same error. I know I have to be doing something basic wrong but
> cant figure it out, anyone know what I am doing wrong. The def is below.

Did you try completely restarting your Python interpreter?  It may be
that you've still got the previous version of your module/function in
memory hence why it's still giving you your old error.  You could try
the reload() built in function to get the interpreter to reload your
previously imported module:
http://docs.python.org/library/functions.html#reload

HTH,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem editing modules and defs

2012-02-24 Thread Walter Prins
Hi,

On 24 February 2012 16:29, David Craig  wrote:
> Hi,
> I am new to python and have made a couple of definitions. I imported them
> and they worked ok except for one which gave me the error "NameError: global
> name 'np' is not defined". I then edited my script for the def to include
> "import numpy as np" saved it and imported the def again. However, it still
> gives me the same error. I know I have to be doing something basic wrong but
> cant figure it out, anyone know what I am doing wrong. The def is below.
> thanks

I see others have responded to another post in more detail so please
feel free to ignore my brief response. :)

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Suggestions for a good intro OO & Python

2012-02-24 Thread Alan Gauld

On 24/02/12 15:43, Sivaram Neelakantan wrote:


Can someone point me to a good intro on OO in Python?  If it does OO
basics too, even better, assuming no prior knowledge of Object
Orientation.


You can try the OOP topic in my tutorial.

It also has some pointers to some more advanced tutors
and books for the next steps...

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Anthony Papillion
Hi Everyone,

I'm learning pyGtk and am developing my first application. I'm trying to
check if a GtkEntry is empty and I'm using the following code:

if txtSearch.get_text() == "":
print "The entry is empty"

This didn't work. So I thought, maybe I need to reference self and tried:

if self.txtSearch.get_text() == "":
print "The entry is empty"

Neither worked. What am I doing wrong?

Thanks1
Anthony
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Prasad, Ramit
>if txtSearch.get_text() == "":
>    print "The entry is empty"

>This didn't work. So I thought, maybe I need to reference self and tried:

>if self.txtSearch.get_text() == "":
>    print "The entry is empty"
>Neither worked. What am I doing wrong?

Please post a more significant code sample as I have no idea from this,
but at least one of those should have given you an error. Always include 
the full error (including stacktrace) you get from Python. Use copy/paste
and do not try and retype or rephrase it. Do not attach a file as many users 
of this list do not receive attachments.

Welcome to the list!
Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Anthony Papillion
On Fri, Feb 24, 2012 at 5:10 PM, Prasad, Ramit
 wrote:
>
> Please post a more significant code sample as I have no idea from this,
> but at least one of those should have given you an error. Always include
> the full error (including stacktrace) you get from Python. Use copy/paste
> and do not try and retype or rephrase it. Do not attach a file as many
> users
> of this list do not receive attachments.

Hi Ramit,

Thanks for the welcome. Basically, that's actually the code. But here
is the complete function that includes the code:

def on_btnSearch_click(self, data=None):
if btnSearch.get_text() == "":
print "Nothing to search"
else:
print "I would do this search"

The code above does nothing. No error, no print, nothing. Any idea?

Thanks!
Anthony
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Alan Gauld

On 24/02/12 23:49, Anthony Papillion wrote:

Add a trace to see if the method ever gets called


def on_btnSearch_click(self, data=None):


   print "I'm in on_btnSearch_click"


 if btnSearch.get_text() == "":
 print "Nothing to search"
 else:
 print "I would do this search"




The code above does nothing. No error, no print, nothing. Any idea?


Where are you looking for the printout?
How are you running it?

If the message I added doesn't print you need to look at how you are 
associating the method with the widget event.


You don't show us enough code for us to tell.
In fact you still don't show us enough to answer the original question 
about how to reference btnSearch. we would need to see where btnSearch 
is created.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Prasad, Ramit
>def on_btnSearch_click(self, data=None):
>if btnSearch.get_text() == "":
>print "Nothing to search"
>else:
>print "I would do this search"

>The code above does nothing. No error, no print, nothing. Any idea?

How are you running this? I assume from an IDE because this should most
likely cause an error. I would recommend trying to run your python script
from the commandline which is much more likely to print an error. 

$python your_script.py

btnSearch.get_text() should be self. btnSearch.get_text()

Typically print statements are not seen in UI applications because they
are not run from command very often or the loop in charge of handling
events swallows them (which is what happens in an IDE). I would recommend
using a popup window or changing the text of a field instead. Or you can
use the python logger and just look at the log file afterwards.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Anthony Papillion
On Fri, Feb 24, 2012 at 6:07 PM, Alan Gauld  wrote:
>
> Add a trace to see if the method ever gets called

The method is definitely getting called. If I remove the attempt to
get the widgets text and replace it with

print "btnSearch has been clicked"

The method is called and the message is printed to the console as expected.

> Where are you looking for the printout?
> How are you running it?

I'm looking for the printout on the console screen. I'm running it by
typing 'python trial.py' in the console.

> If the message I added doesn't print you need to look at how you are
> associating the method with the widget event.
>
> You don't show us enough code for us to tell.
> In fact you still don't show us enough to answer the original question about
> how to reference btnSearch. we would need to see where btnSearch is created.

The entire GUI is created using Glade. In Glade, I've clicked on the
button widget and then the Signals tab. I'm associating the
btnSearch's click event with the on_btnSearch.clicked method. As I
said above, the method is being called, I'm just not able to actually
get the widgets text.

Does that make it clearer?

Thanks!
Anthony
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Anthony Papillion
On Fri, Feb 24, 2012 at 5:55 PM, Prasad, Ramit
 wrote:
>
> How are you running this? I assume from an IDE because this should most
> likely cause an error. I would recommend trying to run your python script
> from the commandline which is much more likely to print an error.
>
> $python your_script.py

Hi Ramit,

I'm running this from terminal in exactly the way you're saying.

> btnSearch.get_text() should be self. btnSearch.get_text()

When I change the code as you suggest, I'm getting this error:

if self.btnSearch.text == "":
AttributeError: 'DocuManager' object has no attribute 'btnSearch'

Here is the entire text of the code I have so far:

#!/usr/bin/env python

import pygtk
pygtk.require("2.0")
import gtk
import sqlite3 as lite

class Manager(object):
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("winMain.glade")
builder.connect_signals(self)
self.window = builder.get_object("winMain")
self.window.show()

conn = None
try:
conn = lite.connect('docs.db')
sql =  "create table if not exists documents(id integer,
name text, location text, tags text)"
c = conn.cursor()
c.execute(sql)
conn.commit()
except lite.Error, e:
print "Error: " + e.args[0]


def on_btnSearch_clicked(self, data=None):
if self.btnSearch.text == "":
print "No text"
else:
print "There is text"

def on_tbExit_clicked(self, data=None):
   exit()


if __name__ == "__main__":
app = Manager()
gtk.main()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Alan Gauld

On 25/02/12 00:17, Anthony Papillion wrote:


The entire GUI is created using Glade. In Glade, I've clicked on the
button widget and then the Signals tab. I'm associating the
btnSearch's click event with the on_btnSearch.clicked method. As I
said above, the method is being called, I'm just not able to actually
get the widgets text.

Does that make it clearer?



Yes thanks, that fills in the gaps nicely.
Unfortunately it also takes you outside my area of
knowledge since I've never used Glade (tried but
couldn't get it to work!)

Hopefully somebody else here knows more...

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Steven D'Aprano

Anthony Papillion wrote:


class Manager(object):
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("winMain.glade")
builder.connect_signals(self)
self.window = builder.get_object("winMain")
self.window.show()

conn = None
try:
conn = lite.connect('docs.db')
sql =  "create table if not exists documents(id integer,
name text, location text, tags text)"
c = conn.cursor()
c.execute(sql)
conn.commit()
except lite.Error, e:
print "Error: " + e.args[0]



Are you aware that the database connection gets made, but not stored anywhere? 
Once the Manager instance is created, the database connection is thrown away.


My guess is that you mean to use self.conn instead of conn in the above.

Which brings me to another point. It seems to me that the above is poor design.

When you create a Manager instance, if something goes wrong with the database 
entry, you end up with an instance with an unspecified, and possibly broken, 
inst.conn. That's bad, because the caller can't trust the value of inst.conn 
to be in a sensible state, and they may not have any easy way to tell the 
difference between inst.conn is safe to use and inst.conn is broken.


In other words, you should use one of these designs instead:

# broken connections are never allowed and are always fatal errors
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("winMain.glade")
builder.connect_signals(self)
self.window = builder.get_object("winMain")
self.window.show()
conn = lite.connect('docs.db')
sql =  ( "create table if not exists documents("
 "id integer, name text, location text, tags text)" )
c = conn.cursor()
c.execute(sql)
conn.commit()
self.conn = conn


# broken connections are allowed and given a warning
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("winMain.glade")
builder.connect_signals(self)
self.window = builder.get_object("winMain")
self.window.show()
try:
conn = lite.connect('docs.db')
sql =  ( "create table if not exists documents("
 "id integer, name text, location text, tags text)" )
c = conn.cursor()
c.execute(sql)
conn.commit()
except lite.Error, e:
print "Warning:", e.args[0]  # Warning, not an error.
conn = None
self.conn = conn


Notice that it is important to set conn = None *after* catching the exception, 
because if you do it before, it will be changed to a broken connection before 
you save it as self.conn.


Also note that you shouldn't frighten users with "Error" when it isn't an 
error, merely a warning, nor should you hide useful tracebacks for fatal errors.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking if a GtkEntry is empty

2012-02-24 Thread Anthony Papillion
On Fri, Feb 24, 2012 at 8:08 PM, Steven D'Aprano 
wrote:
>
> Are you aware that the database connection gets made, but not stored
> anywhere? Once the Manager instance is created, the database connection is
> thrown away.
>
> My guess is that you mean to use self.conn instead of conn in the above.



Hi Steven,

Thanks for all the fantastic feedback! I'm fairly new to Python and still
trying to wrap my head around some of the basic concepts as well as learn
pyGtk at the same time. While I should have known about the problems you
mentioned, I completely spaced them out and good design wasn't really in my
head when I wrote this code, unfortunately.  Thanks for the helpful hints.
Duly noted and implemented :-)

Anthony
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with Python Program

2012-02-24 Thread Carolina Dianne LaCourse
Hi,
I have never programed before and am brand new to python also. I am
trying to create a Hi-Lo game and am not really sure where to start.
These are the instructions that I have. I know that I will need to
import the random number generator and have looked up how to do that.
I understand that I need to ask for raw input from the user and that I
need to be able to use the if elif else to tell the user whether their
number matches or id too high or to low but am just not sure what to
do first. Any advice would be greatly appreciated! I have tried some
online tutorials to get the basics but still am having a really hard
time. I did work with scratch a bit earlier this semester and got
that, but am really struggling with python.

For your second project, you will create a Python guessing game. In
this game, the user will be asked to guess a number between 1 and 100.
For each guess, you will output one of three things:
The user guess is correct -- tell the user he or she won,
asking if he/she wants to play again.
The user guess is too high -- tell him or her so.
The user guess is too low -- tell him or her so.
Your program should be able to run multiple games. That is, after
each game, the user should be asked if they want to play again. If
they type yes, then you pick a new number and play again. If they type
no, then the program should say goodbye and exit. You should keep the
following stats about the player's efforts:
Number of games played
Total number of guesses made
You should output the number of games played as well as the
average number of guess per game. This program will require loops
(nested ones, in fact), an if-elif-else statement, and the use of
Python's random number generator.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python Program

2012-02-24 Thread bob gailer

On 2/24/2012 10:18 PM, Carolina Dianne LaCourse wrote:

Hi,
I have never programed before and am brand new to python also. I am
trying to create a Hi-Lo game and am not really sure where to start.
These are the instructions that I have. I know that I will need to
import the random number generator and have looked up how to do that.
I understand that I need to ask for raw input from the user and that I
need to be able to use the if elif else to tell the user whether their
number matches or id too high or to low but am just not sure what to
do first. Any advice would be greatly appreciated! I have tried some
online tutorials to get the basics but still am having a really hard
time. I did work with scratch

What is scratch?

a bit earlier this semester and got
that, but am really struggling with python.
We get many requests like this. I always wonder why there is a mismatch 
between the course and the student. A beginner's programming class 
should give you the tools you need to solve the problem. Can you help us 
understand why this is not happening for you?


I assume this is not your fault - that there is something wrong with the 
course and/or the instructor.


As a rule we don't write the program for you; we take a look at what 
you've done and help you over the rough spots. Please write any amount 
of code you can and return with that.


For your second project,

What was the first project? How did that go?

  you will create a Python guessing game. In
this game, the user will be asked to guess a number between 1 and 100.
For each guess, you will output one of three things:
 The user guess is correct -- tell the user he or she won,
asking if he/she wants to play again.
 The user guess is too high -- tell him or her so.
 The user guess is too low -- tell him or her so.
 Your program should be able to run multiple games. That is, after
each game, the user should be asked if they want to play again. If
they type yes, then you pick a new number and play again. If they type
no, then the program should say goodbye and exit. You should keep the
following stats about the player's efforts:
 Number of games played
 Total number of guesses made
 You should output the number of games played as well as the
average number of guess per game. This program will require loops
(nested ones, in fact), an if-elif-else statement, and the use of
Python's random number generator.

Do you know how to create a loop? If not, why not?
Do you know how to test for low or high? If not why not?
If your answers to these questions is no then (IMHO) you are in the 
wrong class.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python Program

2012-02-24 Thread Steven D'Aprano

Carolina Dianne LaCourse wrote:

[...]

I understand that I need to ask for raw input from the user and that I
need to be able to use the if elif else to tell the user whether their
number matches or id too high or to low but am just not sure what to
do first. Any advice would be greatly appreciated! I have tried some
online tutorials to get the basics but still am having a really hard
time. I did work with scratch a bit earlier this semester and got
that, but am really struggling with python.


Start by writing down in plain English the steps of how you would play the 
guessing game. This is a called an algorithm, which is something very similar 
to a recipe or a set of instructions. You might have something like this:


(1) Think of a number between 1 and 100, and remember it.
(2) Repeat the following steps until the game is over:
(3) - Ask the person playing for a number between 1 and 100.
(4) - If the number is too low, tell them it is too low.
(5) - If the number is too high, tell them it is too high.
(6) - If the number is equal to the number you thought of, the game is over.

All that makes up *one* game. Then you need instructions to play multiple games:

(a) Play one game, as above.
(b) Repeat the following steps until done:
(c) - Ask the player if they want to play again.
(d) - If they say Yes, play one game, as above.
(e) - Otherwise, we are done.
(f) Finally, print how many games were played, how many guesses were needed, 
and the average number of guesses per game.



Now, you need to change the English instructions to instructions the computer 
can follow, using Python. For example, Step (1) above picks a random number 
and remembers it as the target of the game:


import random
target = random.randint(1, 100)

Step (2) is a bit harder -- it's a loop. You should have learned about while 
loops and for loops. I expect a while loop is better for this, because you 
can't tell ahead of time how many times you need to go round and round the loop.



while guess != target:
Step (3) ask the user for a number, and call it "guess"
if guess < target:
print "too low"
elif guess > target:
print "too high"
# otherwise guess == target so the game will be over


Notice that this isn't exactly Python code. The most obvious problem is the 
line "Step (3)..." which is plain English. You need to replace that with code 
to actually ask the user for a number. (Hint: you will need the raw_input 
function.)


Another problem is that the *first* time you enter the loop, the name "guess" 
isn't defined. You need to give it a value to start with, before the loop. Any 
value will do, so long as it isn't target. I suggest 0.


Does this help you get started? Go ahead and write some code, and see where it 
takes you. Piece by piece, step by step, you should work towards replacing 
each bit of English instruction with some Python code to do that.


You should aim to write code to play *one* game first. Get that right, first, 
then adapt it to play multiple games.


Write some code, see how it works (or where is fails to work), and anything 
that is unclear, come back and ask.




--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor