Re: [Tutor] Loops

2015-04-05 Thread Steven D'Aprano
On Sun, Apr 05, 2015 at 01:11:06PM +0200, Marcus Lütolf wrote:
> Why do I get this traceback with the infinite loop below but not with the
> definitw loop (bottom of mail)?

You forgot to show the definite loop, but the error in the infinite loop 
is explained by the error message. You should read the error message 
carefully, it will often explain the problem you are having. Further 
comments below.

> count = 0
> total = 0
> while True:
> x = raw_input('Enter a number')
> count = count + 1
> total = total + x
> print count, total, (total/count)
>  
> 
> Traceback (most recent call last):
>   File "C:\Python27\enter_a_number.py", line 6, in 
> total = total + x
> TypeError: unsupported operand type(s) for +: 'int' and 'str'

The traceback shows you the line causing the error:

total = total + x

and describes the error: you cannot add an int and a str. Try it at the 
interactive interpreter:

py> 23 + "42"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'str'


The `total` variable starts as an int:

total = 0

and x is a string. Just because you print "Enter a number" doesn't mean 
that Python magically turns x into a number. You are responsible for 
turning the string into a number. Try:

x = int(raw_input('Enter a number'))



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


Re: [Tutor] Loops

2015-04-05 Thread Alan Gauld

On 05/04/15 12:11, Marcus Lütolf wrote:

Why do I get this traceback with the infinite loop below but not with the
definitw loop (bottom of mail)?


I don;t see anyt loops at the bottom.
But as for this one...


count = 0
total = 0

while True:
 x = raw_input('Enter a number')


raw_input reads a character string. You need to converrt it to a number:

  x = int(raw_input('Enter a number') )



 count = count + 1
 total = total + x


Without the conversion you are trying to add a string
to a number which is illegal in Python.


 print count, total, (total/count)



Traceback (most recent call last):
   File "C:\Python27\enter_a_number.py", line 6, in 
 total = total + x
TypeError: unsupported operand type(s) for +: 'int' and 'str'


Which is what the error is telling you.


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Loops

2015-04-05 Thread Mark Lawrence

On 05/04/2015 12:11, Marcus Lütolf wrote:

Why do I get this traceback with the infinite loop below but not with the
definitw loop (bottom of mail)?
Thanks for help, Marcus.

count = 0
total = 0
while True:

 x = raw_input('Enter a number')
 count = count + 1
 total = total + x
 print count, total, (total/count)

Traceback (most recent call last):

   File "C:\Python27\enter_a_number.py", line 6, in 

 total = total + x

TypeError: unsupported operand type(s) for +: 'int' and 'str'



raw_input returns a string, you must convert that to an int (or some 
other numeric type) before you can add it to your total.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[Tutor] Loops

2015-04-05 Thread Marcus Lütolf
Why do I get this traceback with the infinite loop below but not with the
definitw loop (bottom of mail)?
Thanks for help, Marcus.

 

count = 0

total = 0

while True:

x = raw_input('Enter a number')

count = count + 1

total = total + x

print count, total, (total/count)

 

 

Traceback (most recent call last):

  File "C:\Python27\enter_a_number.py", line 6, in 

total = total + x

TypeError: unsupported operand type(s) for +: 'int' and 'str'



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren geprüft.
http://www.avast.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Loops and matrices'

2011-08-29 Thread Peter Otten
Reed DA (Danny) at Aera wrote:

> I have a matrix which contains temperatures. The columns are time, spaced
> 33 seconds apart, and the rows are depth intervals. What I'm trying to do
> is create another matrix that contains the rate of change of temperature
> for each depth. The array is called LS_JULY_11 and the output array should
> be delta_temp

I think you don't need any explicit for-loops:

>>> import numpy as np
>>> july = np.random.randint(0, 100, (3, 4))
>>> july
array([[27, 43, 67, 12],
   [52, 22, 54, 26],
   [70, 81, 61, 49]])
>>> dt = 33.0
>>> july[1:]
array([[52, 22, 54, 26],
   [70, 81, 61, 49]])
>>> july[:-1]
array([[27, 43, 67, 12],
   [52, 22, 54, 26]])
>>> (july[1:]-july[:-1])
array([[ 25, -21, -13,  14],
   [ 18,  59,   7,  23]])
>>> (july[1:]-july[:-1])/dt
array([[ 0.75757576, -0.63636364, -0.39393939,  0.42424242],
   [ 0.54545455,  1.78787879,  0.21212121,  0.6969697 ]])

If rows and columns are swapped in the above, just transpose the matrix 
before you start and again when you're done:

>>> july = july.transpose()
>>> july
array([[27, 52, 70],
   [43, 22, 81],
   [67, 54, 61],
   [12, 26, 49]])
>>> ((july[1:]-july[:-1])/dt).transpose()
array([[ 0.48484848,  0.72727273, -1.6667],
   [-0.90909091,  0.96969697, -0.84848485],
   [ 0., -0.60606061, -0.36363636]])


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


Re: [Tutor] Loops and matrices'

2011-08-29 Thread Steven D'Aprano

Alan Gauld wrote:

On 30/08/11 00:26, Emile van Sebille wrote:


delta_temp(i,j) = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP


delta_temp access and assignment likely wants to be expressed with
brackets rather than parens.


And for those not speaking the US variant of English that'll be square 
brackets as opposed to round brackets! ;-)


[ One of the sources of amusement to me when having my book reviewed was 
the fact that *all* the US reviewers picked up on my use of " 
brackets" to cover [],<>,(), {}. Apparently US usage of brackets is 
limited to []. Something that greatly surprised me and my English, 
Indian and South African colleagues! :-) ]


And Australians and New Zealanders too. Any Canadians want to weigh in 
with an opinion?


Brackets are anything that, er,  brackets an expression (excluding 
quotation marks), where the one on the left is different from the one on 
the right. So:


() round brackets
[] square brackets
{} curly brackets
<> angle brackets

Easier to spell than parenthesis/parentheses, but longer than 
brace/braces :)


Strictly speaking, the chevrons (angle brackets) should be ⟨⟩ rather 
than less than and greater than signs, but they're hard to type at the 
keyboard and look too similar to round brackets in small font sizes.



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


Re: [Tutor] Loops and matrices'

2011-08-29 Thread Alan Gauld

On 30/08/11 00:26, Emile van Sebille wrote:


delta_temp(i,j) = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP


delta_temp access and assignment likely wants to be expressed with
brackets rather than parens.


And for those not speaking the US variant of English that'll be square 
brackets as opposed to round brackets! ;-)


[ One of the sources of amusement to me when having my book reviewed was 
the fact that *all* the US reviewers picked up on my use of " 
brackets" to cover [],<>,(), {}. Apparently US usage of brackets is 
limited to []. Something that greatly surprised me and my English, 
Indian and South African colleagues! :-) ]


--
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] Loops and matrices'

2011-08-29 Thread Emile van Sebille

On 8/29/2011 3:28 PM Reed DA (Danny) at Aera said...

Hi all,

I have a matrix which contains temperatures. The columns are time,
spaced 33 seconds apart, and the rows are depth intervals. What I'm
trying to do is create another matrix that contains the rate of change
of temperature for each depth. The array is called LS_JULY_11 and the
output array should be delta_temp

What I have so far is:-

import numpy

#determine the existing matrix size

columnsize = LS_JULY_11.columnSize()

matrixsize = LS_JULY_11.size()

rowsize = matrixsize/columnsize

#define time step

TIME_STEP = 33

#create matrix size of the same size

delta_temp = numpy.zeros((rowsize,columnsize))

#cycle through all indicies in temperature matrix

for i in rowsize:

 for j in columnsize:

 delta_temp(i,j) = (LS_JULY_11(i,j) -
LS_JULY_11(i,j-1))/TIME_STEP

 j = j+1

 i = i + 1

the error I get is:-

   File "", line 18 (33)

SyntaxError: can't assign to function call


delta_temp access and assignment likely wants to be expressed with 
brackets rather than parens.


Emile



ActivePython 2.6.6.15 (ActiveState Software Inc.) based on
Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> spam(1,2)=6
  File "", line 1
SyntaxError: can't assign to function call
>>>



Help would be greatly appreciated

Thanks

Danny




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


Re: [Tutor] Loops and matrices'

2011-08-29 Thread Prasad, Ramit
Hi Danny,
Most likely you want 
    delta_temp(i,j) = (LS_JULY_11(i,j) - 
LS_JULY_11(i,j-1))/TIME_STEP
 to become (changed the character from '()' to '[]':

    delta_temp[i,j] = (LS_JULY_11(i,j) - 
LS_JULY_11(i,j-1))/TIME_STEP

Basically it thinks "delta_temp(i,j) " is a function call and function calls 
cannot be assigned a value.

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


[Tutor] Loops and matrices'

2011-08-29 Thread Reed DA (Danny) at Aera
Hi all,

I have a matrix which contains temperatures. The columns are time, spaced 33 
seconds apart, and the rows are depth intervals. What I'm trying to do is 
create another matrix that contains the rate of change of temperature for each 
depth. The array is called LS_JULY_11 and the output array should be delta_temp

What I have so far is:-


import numpy

#determine the existing matrix size
columnsize = LS_JULY_11.columnSize()
matrixsize = LS_JULY_11.size()
rowsize = matrixsize/columnsize

#define time step
TIME_STEP = 33


#create matrix size of the same size
delta_temp = numpy.zeros((rowsize,columnsize))

#cycle through all indicies in temperature matrix
for i in rowsize:
for j in columnsize:
delta_temp(i,j) = (LS_JULY_11(i,j) - 
LS_JULY_11(i,j-1))/TIME_STEP
j = j+1
i = i + 1

the error I get is:-

  File "", line 18 (33)
SyntaxError: can't assign to function call

Help would be greatly appreciated
Thanks
Danny
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops

2009-12-08 Thread Lie Ryan

On 12/9/2009 3:18 AM, Rich Lovely wrote:

2009/12/8 spir:

This, of course is a rather dirty, implementation (and probably
version) specific hack, but I can /calculate/ the sequence, using just
one line:


print " ".join(str(i) for i in [x if x<2 else 
(locals()['_[1]'][-1]+locals()['_[1]'][-2]) for x in xrange(20)])

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

(CPython 2.6, on osx10.6)


the best one-liner golf score for now (83 chars, requires python3), 
quite obfuscated:


(lambda*n:n[0](*n))(lambda f,n,a=0,b=1:n<0 or print(a,end=' ')or 
f(f,n-1,b,a+b),19)



and though not a pure one-liner, the most "straightforward" method is 
just a char away (84 chars, python2):


a=[0,1];[a.append(sum(a[-2:]))for x in range(3)][0];print' 
'.join(str(x)for x in a)



if you don't require one-liner you can make it even shorter (81 chars, 
'\n'==1char, requires python2)

a=[0,1]
for x in range(18):a.append(sum(a[-2:]))
print' '.join(str(x) for x in a)

All codes tested on command-line with -c argument (i.e. the shell's 
default repr()-ing of expressions is ignored), result must be printed to 
screen as numbers separated by space (printing with list repr, e.g. [0, 
1, ...] is not acceptable). Trailing space is ignored.



It's slightly more typing than the plain string, but extend it to
about 30 entries, and I think I win?


Think again...


Note to OP: don't _ever_ do it this way in a serious project.


OP: In a real project, readability counts. Inglfng,spcecnts.

PS: Perl fans might complain that their favorite pastime is stolen

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


Re: [Tutor] loops

2009-12-08 Thread Rich Lovely
2009/12/8 spir :
> Lie Ryan  dixit:
>
>> On 12/8/2009 9:39 PM, Dave Angel wrote:
>> > Richard Hultgren wrote:
>> >> a = 0
>> >> b = 1
>> >> count = 0
>> >> max_count = 20
>> >> while count < max_count:
>> >> count = count + 1
>> >> # we need to keep track of a since we change it
>> >> old_a = a # especially here
>> >> old_b = b
>> >> a = old_b
>> >> b = old_a + old_b
>> >> # Notice that the , at the end of a print statement keeps it
>> >> # from switching to a new line
>> >> print old_a,
>> >>
>> >>
>> >>
>> > What's your question or comment?
>> >
>> > If you're just looking for a challenge, I'll point out that the same
>> > result could be gotten with 4 lines of Python.
>>
>> you lose, 1 line is all it takes for me:
>> print "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181"
>
> you lose, I don't even need a one-liner python prog to write a text into 
> whatever stdout may be -- except if remote ;-)
>
> Denis
> 
>
> la vita e estrany
>
> http://spir.wikidot.com/
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

This, of course is a rather dirty, implementation (and probably
version) specific hack, but I can /calculate/ the sequence, using just
one line:

>>> print " ".join(str(i) for i in [x if x<2 else 
>>> (locals()['_[1]'][-1]+locals()['_[1]'][-2]) for x in xrange(20)])
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

(CPython 2.6, on osx10.6)

It's slightly more typing than the plain string, but extend it to
about 30 entries, and I think I win?


Note to OP: don't _ever_ do it this way in a serious project.

-- 
Rich "Roadie Rich" Lovely

There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops

2009-12-08 Thread spir
Lie Ryan  dixit:

> On 12/8/2009 9:39 PM, Dave Angel wrote:
> > Richard Hultgren wrote:
> >> a = 0
> >> b = 1
> >> count = 0
> >> max_count = 20
> >> while count < max_count:
> >> count = count + 1
> >> # we need to keep track of a since we change it
> >> old_a = a # especially here
> >> old_b = b
> >> a = old_b
> >> b = old_a + old_b
> >> # Notice that the , at the end of a print statement keeps it
> >> # from switching to a new line
> >> print old_a,
> >>
> >>
> >>
> > What's your question or comment?
> >
> > If you're just looking for a challenge, I'll point out that the same
> > result could be gotten with 4 lines of Python.
> 
> you lose, 1 line is all it takes for me:
> print "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181"

you lose, I don't even need a one-liner python prog to write a text into 
whatever stdout may be -- except if remote ;-)

Denis


la vita e estrany

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


Re: [Tutor] loops

2009-12-08 Thread Lie Ryan

On 12/8/2009 9:39 PM, Dave Angel wrote:

Richard Hultgren wrote:

a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
# we need to keep track of a since we change it
old_a = a # especially here
old_b = b
a = old_b
b = old_a + old_b
# Notice that the , at the end of a print statement keeps it
# from switching to a new line
print old_a,




What's your question or comment?

If you're just looking for a challenge, I'll point out that the same
result could be gotten with 4 lines of Python.


you lose, 1 line is all it takes for me:
print "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181"

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


Re: [Tutor] loops

2009-12-08 Thread Dave Angel

Richard Hultgren wrote:

a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
# we need to keep track of a since we change it
old_a = a# especially here
old_b = b
a = old_b
b = old_a + old_b
# Notice that the , at the end of a print statement keeps it
# from switching to a new line
print old_a,



  
  

What's your question or comment?

If you're just looking for a challenge, I'll point out that the same 
result could be gotten with 4 lines of Python.


DaveA

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


Re: [Tutor] loops

2009-12-07 Thread Kent Johnson
Is there a question here?
Please skip the giant type size.

Kent

On Mon, Dec 7, 2009 at 2:53 PM, Richard Hultgren  wrote:
> a = 0
> b = 1
> count = 0
> max_count = 20
> while count < max_count:
>     count = count + 1
>     # we need to keep track of a since we change it
>     old_a = a# especially here
>     old_b = b
>     a = old_b
>     b = old_a + old_b
>     # Notice that the , at the end of a print statement keeps it
>     # from switching to a new line
>     print old_a,
>
>
> ___
> Tutor maillist  -  tu...@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] loops

2009-12-07 Thread Richard Hultgren
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
    count = count + 1
    # we need to keep track of a since we change it
    old_a = a# especially here
    old_b = b
    a = old_b
    b = old_a + old_b
    # Notice that the , at the end of a print statement keeps it
    # from switching to a new line
    print old_a,



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


Re: [Tutor] loops

2009-04-29 Thread Lie Ryan

Norman Khine wrote:

hello,
i have the following code:


Uhh... 5 levels deep of nesting, and from the hint that you used 
self.blah earlier this is inside a class which adds a minimum of two 
extra levels, in total of 7 levels nesting... We're in deep trouble.



is there a way to optimise the loop for 'formats'


In this loop:

for item in result:
print item.abspath
item = self.get_handler(item.abspath)
namespace['item_title'] = item.get_property('dc:title')
if isinstance(training, Training):
namespace['item_url'] = item.abspath
else:
# Need to strip the '/companies' from the path
#namespace['item_url'] = Path(item.abspath)[1:]
namespace['item_url'] = Path(item.abspath)

You assigned namespace['item_title'] and namespace['item_url'] several 
times throughout the loop, which means only the last item in result 
would have any lasting significance to the value of 
namespace['item_title'] and namespace['item_url']. You may be able to 
just use result[-1] to directly get the last item.


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


Re: [Tutor] loops

2009-04-29 Thread Kent Johnson
On Wed, Apr 29, 2009 at 3:05 AM, Norman Khine  wrote:
> hello,
> i have the following code:
>
> if unique_id is not None:
>    training = self.get_site_root()
>    from training import Training
>    # link back to news item
>    root = context.root
>    formats = ['itinerary', 'news']
>    for document in formats:
>        results = root.search(format=document, unique_id=unique_id)

What is root here? What are the allowed parameters for root.search()?

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


Re: [Tutor] loops

2009-04-29 Thread spir
Le Wed, 29 Apr 2009 09:42:44 +0200,
"A.T.Hofkamp"  s'exprima ainsi:

> Norman Khine wrote:
> > hello,
> > i have the following code:
> > 
> > if unique_id is not None:
> > training = self.get_site_root()
> > from training import Training
> > # link back to news item
> > root = context.root
> > formats = ['itinerary', 'news']
> > for document in formats:
> > results = root.search(format=document, unique_id=unique_id)
> > if results:
> 
> Instead of processing results from each search directly, why not first
> collect results from all formats, followed by processing of the collected
> results?
> 
> ie something like
> 
> results = []
> for doc in formats:
> results.extend(root.search())
> 
> for result in results:
> 
> 
> This does not give you better performance. However, it does give you the
> room to re-organize the searching.
> 
> 
> In the above, you can now replace the first loop by something like
> 
> results = root.search_all_formats(formats, unique_id)
> 
> 
> Does this help?
> 
> Albert

I find the logic far too complicated, as shown by the outline of the code. 
You can be sure that in most cases (but not all?) the major complications do 
not lie in the problem, but in the programmer's views on it. So I would try and 
find other approaches to simplify the algorithm.
Also, you can abstract some of the problematic aspects of the process into 
funcs, that can each cope with a "limited and well-delimited" part of the 
problem's field. Hope I'm clear and this helps...

def foo(...):
   ...
def bar(...):
   ...
def bazzz(...):
   ...
def blurp(...):
   ...

if blurp():
   foo(...)
   while bazzz(...):
  bar(...)

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops

2009-04-29 Thread A.T.Hofkamp

Norman Khine wrote:

hello,
i have the following code:

if unique_id is not None:
training = self.get_site_root()
from training import Training
# link back to news item
root = context.root
formats = ['itinerary', 'news']
for document in formats:
results = root.search(format=document, unique_id=unique_id)
if results:


Instead of processing results from each search directly, why not first collect 
results from all formats, followed by processing of the collected results?


ie something like

results = []
for doc in formats:
   results.extend(root.search())

for result in results:
   

This does not give you better performance. However, it does give you the room 
to re-organize the searching.



In the above, you can now replace the first loop by something like

results = root.search_all_formats(formats, unique_id)


Does this help?

Albert

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


[Tutor] loops

2009-04-29 Thread Norman Khine
hello,
i have the following code:

if unique_id is not None:
training = self.get_site_root()
from training import Training
# link back to news item
root = context.root
formats = ['itinerary', 'news']
for document in formats:
results = root.search(format=document, unique_id=unique_id)
if results:
result = results.get_documents()
for item in result:
print item.abspath
item = self.get_handler(item.abspath)
namespace['item_title'] = item.get_property('dc:title')
if isinstance(training, Training):
namespace['item_url'] = item.abspath
else:
# Need to strip the '/companies' from the path
#namespace['item_url'] = Path(item.abspath)[1:]
namespace['item_url'] = Path(item.abspath)
else:
namespace['item_title'] = None
namespace['item_url'] = None

is there a way to optimise the loop for 'formats'

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


Re: [Tutor] Loops

2009-02-14 Thread pa yo
Thanks Alan.

after a few hours scratching my head I finally fixed it by removing
all the indents and remaking them in the correct position.

Payo


On Sat, Feb 14, 2009 at 1:52 AM, Alan Gauld  wrote:
> "pa yo"  wrote
>
>> The way I have come up with to solve this problem is to put the
>> following loop in:
>>
 rawfeed = feedparser(http//twitter.com/foobar)
 feedstring = rawfeed.split('=',1)#this splits the feed at the
 first "="
 headline = feedstring[0]#this is the text infront of
 the "=" sign.
 if len(headlinestring) == len(rawfeed)#ie. if the split hasn't
 worked they will be exactly the same >>> body = "\x7b\x7bEmpty\x7d\x7d"
#this adds an "{{Empty}}" template to the wiki
 else:
body = feedstring[1]
>
> Sorry, where is the loop?
>
>> But I can't get it to work - I have tried various indents and break
>> and continues - but I don't know enough about loops to identify what I
>> have done wrong.
>
> I'm confused, there is no loop only a conditional statement (if/else)
> The only loops supported in Python are for and while (OK you
> could count list comprehensions/generator expressions too) and
> neither of them are in your code.
>
> However you don't tell us what is happening that you don;t expect.
> Are you getting an error message? If so what (all of it please)?
> Or is it just the output that is different to what you expect?
> if so what did you expect and what did you get?
>
> And finally which version of Python and which OS please?
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> 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] Loops

2009-02-13 Thread Alan Gauld

"pa yo"  wrote


The way I have come up with to solve this problem is to put the
following loop in:


rawfeed = feedparser(http//twitter.com/foobar)
feedstring = rawfeed.split('=',1)#this splits the feed at 
the first "="
headline = feedstring[0]#this is the text 
infront of the "=" sign.
if len(headlinestring) == len(rawfeed)#ie. if the split hasn't 
worked they will be exactly the same >>> body = 
"\x7b\x7bEmpty\x7d\x7d"#this adds an "{{Empty}}" template 
to the wiki

else:
body = feedstring[1]


Sorry, where is the loop?


But I can't get it to work - I have tried various indents and break
and continues - but I don't know enough about loops to identify what 
I

have done wrong.


I'm confused, there is no loop only a conditional statement (if/else)
The only loops supported in Python are for and while (OK you
could count list comprehensions/generator expressions too) and
neither of them are in your code.

However you don't tell us what is happening that you don;t expect.
Are you getting an error message? If so what (all of it please)?
Or is it just the output that is different to what you expect?
if so what did you expect and what did you get?

And finally which version of Python and which OS please?

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



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


[Tutor] Loops

2009-02-13 Thread pa yo
I need some help.

I have written a filter called Peqibot that takes posts from Twitter
and makes them into wikipages on peqipedia.com

So if you post the following message on Twitter:

>@peqi Tallinn=The capital city of [[Estonia]].

It makes a page on peqipedia.com with "Tallinn" as the headline and
with the article text being "The captial city of [[Estonia]]."

... it seems to be working ok - but I discovered that if someone posts
a message starting with "@peqi" but without an "=" sign the program
crashes.

The way I have come up with to solve this problem is to put the
following loop in:

>> rawfeed = feedparser(http//twitter.com/foobar)

>> feedstring = rawfeed.split('=',1)#this splits the feed at the first 
>> "="

>> headline = feedstring[0]#this is the text infront of the 
>> "=" sign.

>> if len(headlinestring) == len(rawfeed)#ie. if the split hasn't worked 
>> they will be exactly the same length

>> body = "\x7b\x7bEmpty\x7d\x7d"#this adds an "{{Empty}}" template 
>> to the wiki

>> else:

>> body = feedstring[1]

>> #here I use urllib to encode a post from headline and body that can be 
>> posted to the wiki.

But I can't get it to work - I have tried various indents and break
and continues - but I don't know enough about loops to identify what I
have done wrong.

Any advice or suggestions would be great. (it's my first program so
there might well be a better way to avoid this problem in the first
place).

Best wishes

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


Re: [Tutor] loops, variables and strings

2008-07-05 Thread bob gailer

James wrote:

All,

I'm trying to do something pretty simple, but I can't seem to get
Python to behave nicely. :)

I'd like to automate a script that sends out three or four lists in an
e-mail. I have a function dedicated to sending e-mail that will take a
string variable, slap it in a message, and send it on its merry way.

The issue, however, is that I can't format the string I want
correctly. I'd like to do something similar to the following:

myString = """Hello. Below is an automated e-mail with important statistics.

The following user accounts expired today:
 - 
 - 
...

The following user accounts will expire within the next 7 days:
 - 
 - 
...

The following user accounts will expire in the next month:
 - 
 - """

I've written some code that actually does include a list of users, like this:

myString = """Hello. Below is an automated e-mail with important statistics.

The following user accounts expired today:
%s

The following user accounts will expire within the next 7 days:
%s

The following user accounts will expire in the next month:
%s""" % (expiredAccounts,toExpire7,toExpire30,),

  
Remove the trailing , in the last line. It is causing myString to be a 
tuple.



Of course in this scenario, the variables in the parenthesis are
strings with newlines in them. But when I do a 'print myString', it
shows everything in one line, including the '\n' characters at the end
of every user account listed.

Thoughts on what I may be doing wrong?



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

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


Re: [Tutor] loops, variables and strings

2008-07-05 Thread Monika Jisswel
maybe StringIO ?

MsgBody = StringIO.StringIO()
print >> MsgBody, "Hello. Below is an automated e-mail with important
statistics."
print >> MsgBody, ""#empty line
print >> MsgBody, ""#empty line
print >> MsgBody, "The following user accounts expired today:"
print >> MsgBody, " - " % (var1, Name1)
print >> MsgBody, " - " % (var2, Name2)
...
< More code here >
...

MSGBODY = MsgBody.getvalue()  # use MSGBODY in you Email.




2008/7/5 James <[EMAIL PROTECTED]>:

> All,
>
> I'm trying to do something pretty simple, but I can't seem to get
> Python to behave nicely. :)
>
> I'd like to automate a script that sends out three or four lists in an
> e-mail. I have a function dedicated to sending e-mail that will take a
> string variable, slap it in a message, and send it on its merry way.
>
> The issue, however, is that I can't format the string I want
> correctly. I'd like to do something similar to the following:
>
> myString = """Hello. Below is an automated e-mail with important
> statistics.
>
> The following user accounts expired today:
>  - 
>  - 
> ...
>
> The following user accounts will expire within the next 7 days:
>  - 
>  - 
> ...
>
> The following user accounts will expire in the next month:
>  - 
>  - """
>
> I've written some code that actually does include a list of users, like
> this:
>
> myString = """Hello. Below is an automated e-mail with important
> statistics.
>
> The following user accounts expired today:
> %s
>
> The following user accounts will expire within the next 7 days:
> %s
>
> The following user accounts will expire in the next month:
> %s""" % (expiredAccounts,toExpire7,toExpire30,),
>
> Of course in this scenario, the variables in the parenthesis are
> strings with newlines in them. But when I do a 'print myString', it
> shows everything in one line, including the '\n' characters at the end
> of every user account listed.
>
> Thoughts on what I may be doing wrong?
>
> Thanks!
> - j
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] loops, variables and strings

2008-07-05 Thread James
All,

I'm trying to do something pretty simple, but I can't seem to get
Python to behave nicely. :)

I'd like to automate a script that sends out three or four lists in an
e-mail. I have a function dedicated to sending e-mail that will take a
string variable, slap it in a message, and send it on its merry way.

The issue, however, is that I can't format the string I want
correctly. I'd like to do something similar to the following:

myString = """Hello. Below is an automated e-mail with important statistics.

The following user accounts expired today:
 - 
 - 
...

The following user accounts will expire within the next 7 days:
 - 
 - 
...

The following user accounts will expire in the next month:
 - 
 - """

I've written some code that actually does include a list of users, like this:

myString = """Hello. Below is an automated e-mail with important statistics.

The following user accounts expired today:
%s

The following user accounts will expire within the next 7 days:
%s

The following user accounts will expire in the next month:
%s""" % (expiredAccounts,toExpire7,toExpire30,),

Of course in this scenario, the variables in the parenthesis are
strings with newlines in them. But when I do a 'print myString', it
shows everything in one line, including the '\n' characters at the end
of every user account listed.

Thoughts on what I may be doing wrong?

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


Re: [Tutor] Loops and modules

2007-12-06 Thread bhaaluu
On Dec 6, 2007 8:38 AM, richard west <[EMAIL PROTECTED]> wrote:
>  heres a partial solution. theres no error checking on the Raw Input and you
> have to type in you last number and press return, before the loop will
> break, but its a start!

And modifying  your modifications makes it work even a little better:
###
#!/usr/bin/python

import random
import time
import threading

class Timer(threading.Thread):
def __init__(self, seconds):
   self.runTime = seconds
   threading.Thread.__init__(self)
def run(self):
global running
time.sleep(self.runTime)
print " "
print "Buzzz!!! Time's up!"
running = False

t = Timer(30)
t.start()
startNum = random.choice(range(1, 9))
newNum = startNum + 7
score = 0
running = True
print 'Start with the number ', startNum, '.  Then continuously add 7
to that number until the timer runs out.  You have 30 seconds.'

while running:
if running == True:
 answer = int(raw_input('Enter your answer: '))
 if answer == newNum:
   print 'That is correct!  Keep going.'
   score = score + 5
   newNum = newNum + 7
   print 'Your score is ', score
 else:
   print 'That is incorrect.  Please try again.'
else:
answer = 0
print ' '
print 'Your total score was: ', score
###

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

> #!/usr/bin/python
> # Filename : math_test.py
>
> import time
> import threading
> class Timer(threading.Thread):
> def __init__(self, seconds):
>self.runTime = seconds
>threading.Thread.__init__(self)
> def run(self):
> global running
> time.sleep(self.runTime)
> print " "
> print "Buzzz!!! Time's up!"
> running = False
> t = Timer(30)
> t.start()
>
> import random
> startNum = random.choice(range(1, 9))
> newNum = startNum + 7 # im assuming you want the first number the user to
> type as the startnum +7,its not too clear.
> score = 0
> running = True
>
> print 'Start with the number ', startNum, '.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
>
> while running:
> print running
> answer = int(raw_input('Enter your answer: '))
> if running == True:
>  if answer == newNum:
>print 'That is correct!  Keep going.'
>score = score + 5
> newNum = newNum+7
>print 'Your score is ', score
> else:
>print 'That is incorrect.  Please try again.'
> print ' '
> print 'you total score was ', score
>
> On Dec 6, 2007 6:15 PM, <[EMAIL PROTECTED]> wrote:
> > Send Tutor mailing list submissions to
> >tutor@python.org
> >
> > To subscribe or unsubscribe via the World Wide Web, visit
> > http://mail.python.org/mailman/listinfo/tutor
> > or, via email, send a message with subject or body 'help' to
> >[EMAIL PROTECTED]
> >
> > You can reach the person managing the list at
> >[EMAIL PROTECTED]
> >
> > When replying, please edit your Subject line so it is more specific
> > than "Re: Contents of Tutor digest..."
> >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Loops and modules

2007-12-06 Thread richard west
 heres a partial solution. theres no error checking on the Raw Input and you
have to type in you last number and press return, before the loop will
break, but its a start!

#!/usr/bin/python
# Filename : math_test.py

import time
import threading
class Timer(threading.Thread):
def __init__(self, seconds):
   self.runTime = seconds
   threading.Thread.__init__(self)
def run(self):
global running
time.sleep(self.runTime)
print " "
print "Buzzz!!! Time's up!"
running = False
t = Timer(30)
t.start()

import random
startNum = random.choice(range(1, 9))
newNum = startNum + 7 # im assuming you want the first number the user to
type as the startnum +7,its not too clear.
score = 0
running = True

print 'Start with the number ', startNum, '.  Then continuously add 7 to
that number until the timer runs out.  You have 30 seconds.'

while running:
print running
answer = int(raw_input('Enter your answer: '))
if running == True:
 if answer == newNum:
   print 'That is correct!  Keep going.'
   score = score + 5
newNum = newNum+7
   print 'Your score is ', score
else:
   print 'That is incorrect.  Please try again.'
print ' '
print 'you total score was ', score

On Dec 6, 2007 6:15 PM, <[EMAIL PROTECTED]> wrote:

> Send Tutor mailing list submissions to
>tutor@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>[EMAIL PROTECTED]
>
> You can reach the person managing the list at
>[EMAIL PROTECTED]
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: Best way of learning (bhaaluu)
>   2. Re: how to accept an integer? (Alan Gauld)
>   3. Mail? What's that? (Ricardo Ar?oz)
>   4. Re: Button 1 Motion Event (Luke Paireepinart)
>   5. While Loops and Modules (earlylight publishing)
>   6. Re: Mail? What's that? (Luke Paireepinart)
>   7. Re: Best way of learning (Remco Gerlich)
>
>
> --
>
> Message: 1
> Date: Wed, 5 Dec 2007 18:50:04 -0500
> From: bhaaluu <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Best way of learning
> To: andy <[EMAIL PROTECTED]>
> Cc: tutor@python.org
> Message-ID:
><[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=ISO-8859-1
>
> On Dec 5, 2007 5:43 PM, andy <[EMAIL PROTECTED]> wrote:
> > Dear Pythonistas
> >
> [snip]
> >
> > So, after this long-winded introduction, I was hoping to pick the wisdom
> > of this list to get some pointers of what to do/not to do to make the
> > most effective use of the few hours I have to learn how to program using
> > Python. So, any advice for someone in their mid-40s who would like to
> > learn Python in a more methodical and effective manner?
> >
> > Thanks in anticipation.
> >
> > Andy
>
> It sounds to me like a good book or two would be just the thing for you.
> May I suggest:
> Learning Python by Mark Lutz
> and
> Programming Python Third Edition by the same author.
>
> Happy Programming!
> --
> b h a a l u u at g m a i l dot c o m
> http://www.geocities.com/ek.bhaaluu/python/index.html
>
>
> --
>
> Message: 2
> Date: Wed, 5 Dec 2007 23:51:59 -
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] how to accept an integer?
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>reply-type=original
>
> "Mahesh N" <[EMAIL PROTECTED]> wrote
>
> > More over i find python to be a little sluggish after having worked
> > with C
> > and Java.
>
> If you translate C or Java code into python you will usually
> get a less than optimal implementation. Python should be
> barely slower than Java and often faster. Compared to
> C - yes there is a slow-down.
>
> But even in C you can use tools like Psycho and Pyrex to
> speed up critical sections to near C speeds if the problem fits.
> Or rewrite the critical section in C and wrap it as a module
> using SWIG. Thats how most of the performance ritical modules
> in the library are written. Where the major bottleneck is I/O
> work like database disk access or GUI or network sockets
> then you should find Python fast enough.
>
> > can someone temme where python is most applicable?
> > server side scripting? am i guessing it right?
>
> Python has been used in almost every form of programming
> from image processing and database manipulation to games
> programming and web server development. Do a search on
> Source Forge for projects using Python for an example of
> the variety.
>
> I'd avoid operating systems, device drivers and hard real-time
> applications though.
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http:

Re: [Tutor] loops to assign variables

2006-07-26 Thread Alan Gauld
I'm reading the gmane news archive to see what I missed
while on vacation and noticed this. Sorry the response is
so late...

"John CORRY" <[EMAIL PROTECTED]> wrote

> For example, I have 30 textentry boxes numbered from entry20 to 
> entry50.
> I have used the following code to assign the entryboxes to a local 
> name.
>
> text20 = self.wTree.get_widget("entry20")
> text21 = self.wTree.get_widget("entry21")

This is not a resonse to Johns original request but a general
comment on variable naming. It seems quite common in GUI
work for folks to use this style of entryN, buttonM etc.

But its not very programmer friendly! We wouldn't normally
call our variables var1, var2 etc it makes the intent of the code
much harder to comprehend. So we choose meaningful variable
names like width, height, name, location etc.

So why not do the same with GUI widgets? I usually prepend
a short code to indicate the type of widget, and either use the
label text or action name for the vatriable. Thus

eName  an entry widget for holding the name and it has
an associated label text of Name

bSave -- a button that has an assaociated action
function called save()

A one or two letter prefix should cover all widget types and
it makes the code much easier to read! Even if using GUI
builder tools it is nearly always possible to rename the
widget from the default widgetXX type name to something
meaningful using the property editor.

> I have had a go at writing a loop for the above 30 textentry boxes. 
> It
> is below, but it does not work.

If you need to loop over widgets in a collection the best way
is to simply add the widgets to a collection.

for widget in widgets:
widget.doSomething()

Or use a dictionary:

widgets = {'Name': eName, 'Save': bSave, ...}
for widget in widgets:

in fact usually you can just navigate the widget containment
tree to access all the widgets at a given level.

Even if you are creating the widgets in bulk and don't have specific
names for each field you can still do the same thing and group
them together with a name for the group. Then load the entry
widgets into a list named by the group, for example of you have
a set of 5 arbitrary search strings that a user can specify,
you define a list called searchStrings and add the widgets to that:

for n in range(5):
searchStrings.append(Entry(args here))

Now we can access the seach strings with

for entry in searchStrings:
 searchString += entry.getval()

mydata.search(searchString)

Or similar techniques. There is hardly ever a good case for
using generic widgetXXX type names IMHO.

Just some stylistic considerations.

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



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


Re: [Tutor] loops to assign variables

2006-07-23 Thread Alan Gauld
I've been on vacation so missed the start of this, apologies 
if i'm missing a point somewhere but...

> Ah. I see.  A copy, eh?  Or, at least a new dictionary separate
> from the "real" namespace.  OK.  I don't know why locals() returns
> a copy as opposed to the original, 

What else can it do?
When you enter a function you enter a new namespace.
It starts out containing the global names and any parameters 
to the function then adds new names as they are created 
plus overrides any global names that get replaced with 
local versions.

It can only do that if it is working on a copy of the global 
namespace to start with otherwise it would be polluting the 
global namespace with local functon versions and in a 
multithreaded environment creating havoc across threads!...

I hope I haven't missed the point and have added some 
clarification, if not forgive me for butting in late! :-)

Alan G.

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


Re: [Tutor] loops to assign variables

2006-07-22 Thread Dave Kuhlman
On Sat, Jul 22, 2006 at 01:41:17PM -0400, Kent Johnson wrote:
> Dave Kuhlman wrote:

[snip]

> > And, also, that's why the following statements all have exactly
> > the same effect:
> >
> > total = 5
> > locals()['total'] = 5
> > exec('total = 5')
> 
> You're not in the mood to believe the docs today, eh? Yes, locals() 
> returns a dict and yes, you can modify it. And yes, "changes may not 
> affect the values of local variables used by the interpreter." In 
> particular modifying locals() inside a function doesn't do what you 
> think it will:
> 
> In [14]: def badlocals():
>: locals()['total'] = 5
>: print total
>:
> 
> In [15]: badlocals
> Out[15]: 
> 
> In [16]: badlocals()
> ---
> exceptions.NameError Traceback (most 
> recent call last)
> 
> F:\Bio\BIOE480\Final project\SequenceAlignment\
> 
> F:\Bio\BIOE480\Final project\SequenceAlignment\ in 
> badlocals()
> 
> NameError: global name 'total' is not defined

Good lord.  I feel queasy.  I think I just felt the ground move
under me.  (We in California near the fault line are sensitive
that way.)  What is the explanation of this?

> 
> At global scope, locals() == globals() and modifying it affects the 
> global namespace. In function scope, I believe locals() is actually a 
> copy of the real namespace.

Ah. I see.  A copy, eh?  Or, at least a new dictionary separate
from the "real" namespace.  OK.  I don't know why locals() returns
a copy as opposed to the original, but at least that explains the
results of the example you give.  And, the sickening feeling of
dread has gone away, the feeling or dread one has when the
fundamental structure of the (Python) world has been turned upside
down.

Thanks for correcting me and for clarification.  And, looks like
Lloyd was right.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops to assign variables

2006-07-22 Thread Kent Johnson
Dave Kuhlman wrote:
> On Sat, Jul 22, 2006 at 11:37:38AM -0400, Python wrote:
>   
>>
>> Well the reference documentation says:
>>
>> locals(
>> )
>> Update and return a dictionary representing the current local
>> symbol table. Warning: The contents of this dictionary should
>> not be modified; changes may not affect the values of local
>> variables used by the interpreter.
>>
>> I believe the compiler thinks it knows of all the local variables, so I
>> think assignment to locals() is likely to lead to grief even it appears
>> to work in simple test cases.
>>
>> 
> But, (and I'm going off-topic here and possibly into the ditch
> along the side of the road) ..., locals() returns a dictionary.
> It's a dictionary like any other dictionary.  And, it is that
> dictionary which Python uses to check for the existence of a
> variable *at runtime*.  Yes. That's right.  Python actually does a
> dictionary look-up for each variable at runtime.  This is *not* a
> flaw; it is part of the object model and execution model of
> Python.  And, that's why compile-time (static) type checking in
> Python is either impossible or would require type inference.
>
> And, also, that's why the following statements all have exactly
> the same effect:
>
> total = 5
> locals()['total'] = 5
> exec('total = 5')

You're not in the mood to believe the docs today, eh? Yes, locals() 
returns a dict and yes, you can modify it. And yes, "changes may not 
affect the values of local variables used by the interpreter." In 
particular modifying locals() inside a function doesn't do what you 
think it will:

In [14]: def badlocals():
   : locals()['total'] = 5
   : print total
   :

In [15]: badlocals
Out[15]: 

In [16]: badlocals()
---
exceptions.NameError Traceback (most 
recent call last)

F:\Bio\BIOE480\Final project\SequenceAlignment\

F:\Bio\BIOE480\Final project\SequenceAlignment\ in 
badlocals()

NameError: global name 'total' is not defined

At global scope, locals() == globals() and modifying it affects the 
global namespace. In function scope, I believe locals() is actually a 
copy of the real namespace.

Kent

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


Re: [Tutor] loops to assign variables

2006-07-22 Thread Dave Kuhlman
On Sat, Jul 22, 2006 at 11:37:38AM -0400, Python wrote:
> On Sat, 2006-07-22 at 17:18 +0200, Karl Pflästerer wrote:
> > On 22 Jul 2006, [EMAIL PROTECTED] wrote:
> > 
> > >
> > > On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
> > >> Hi,
> > >>  
> > >> I am refactoring my code.  I am trying to reduce the amount of lines
> > >> by using more loops.  I tend to use copy and paste a lot instead of
> > >> writing a loop to do the work.
> > >>  
> > >> For example, I have 30 textentry boxes numbered from entry20 to
> > >> entry50.
> > >> I have used the following code to assign the entryboxes to a local
> > >> name.
> > >>  
> > >> text20 = self.wTree.get_widget("entry20")
> > >> text21 = self.wTree.get_widget("entry21")
> > >>  
> > >> I have had a go at writing a loop for the above 30 textentry boxes.
> > >> It is below, but it does not work.  
> > >>  
> > >> for x in range(20,51):
> > >> ent = "entry%s" % (str(x))
> > >>
> > >> text_x = self.wTree.get_widget(ent)
> > >>  
> > >> Is it possible to do what I want it to do?  
> > >
> > > NO.  You are looking to create local variables "on the fly".  But there
> > > is a simple solution that accomplishes what you really want.
> > 
> > The "no" is not absolutely right IMO.  He could write directly in the
> > dictionary he gets when he calls locals() (but I think you're right in
> > saying that this is only seldom a good idea).
> 
> Well the reference documentation says:
> 
> locals(
> )
> Update and return a dictionary representing the current local
> symbol table. Warning: The contents of this dictionary should
> not be modified; changes may not affect the values of local
> variables used by the interpreter.
> 
> I believe the compiler thinks it knows of all the local variables, so I
> think assignment to locals() is likely to lead to grief even it appears
> to work in simple test cases.
> 

Lloyd is spot-on in telling you to avoid creating variables from
strings.  There almost always is a better way, which members of
this list seem to have to repeat once each week.

But, (and I'm going off-topic here and possibly into the ditch
along the side of the road) ..., locals() returns a dictionary.
It's a dictionary like any other dictionary.  And, it is that
dictionary which Python uses to check for the existence of a
variable *at runtime*.  Yes. That's right.  Python actually does a
dictionary look-up for each variable at runtime.  This is *not* a
flaw; it is part of the object model and execution model of
Python.  And, that's why compile-time (static) type checking in
Python is either impossible or would require type inference.

And, also, that's why the following statements all have exactly
the same effect:

total = 5
locals()['total'] = 5
exec('total = 5')

But, again, as Lloyd said, don't do that.  (1) Use a dictionary of
your own and do a look up.  Or, (2) implement a class that does a
lookup.  Or, (3) use one of the other suggestion made on this
list.

Dave



-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops to assign variables

2006-07-22 Thread Python
On Sat, 2006-07-22 at 17:18 +0200, Karl Pflästerer wrote:
> On 22 Jul 2006, [EMAIL PROTECTED] wrote:
> 
> >
> > On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
> >> Hi,
> >>  
> >> I am refactoring my code.  I am trying to reduce the amount of lines
> >> by using more loops.  I tend to use copy and paste a lot instead of
> >> writing a loop to do the work.
> >>  
> >> For example, I have 30 textentry boxes numbered from entry20 to
> >> entry50.
> >> I have used the following code to assign the entryboxes to a local
> >> name.
> >>  
> >> text20 = self.wTree.get_widget("entry20")
> >> text21 = self.wTree.get_widget("entry21")
> >>  
> >> I have had a go at writing a loop for the above 30 textentry boxes.
> >> It is below, but it does not work.  
> >>  
> >> for x in range(20,51):
> >> ent = "entry%s" % (str(x))
> >>
> >> text_x = self.wTree.get_widget(ent)
> >>  
> >> Is it possible to do what I want it to do?  
> >
> > NO.  You are looking to create local variables "on the fly".  But there
> > is a simple solution that accomplishes what you really want.
> 
> The "no" is not absolutely right IMO.  He could write directly in the
> dictionary he gets when he calls locals() (but I think you're right in
> saying that this is only seldom a good idea).

Well the reference documentation says:

locals(
)
Update and return a dictionary representing the current local
symbol table. Warning: The contents of this dictionary should
not be modified; changes may not affect the values of local
variables used by the interpreter.

I believe the compiler thinks it knows of all the local variables, so I
think assignment to locals() is likely to lead to grief even it appears
to work in simple test cases.

-- 
Lloyd Kvam
Venix Corp

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


Re: [Tutor] loops to assign variables

2006-07-22 Thread Karl Pflästerer
On 22 Jul 2006, [EMAIL PROTECTED] wrote:

>
> On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
>> Hi,
>>  
>> I am refactoring my code.  I am trying to reduce the amount of lines
>> by using more loops.  I tend to use copy and paste a lot instead of
>> writing a loop to do the work.
>>  
>> For example, I have 30 textentry boxes numbered from entry20 to
>> entry50.
>> I have used the following code to assign the entryboxes to a local
>> name.
>>  
>> text20 = self.wTree.get_widget("entry20")
>> text21 = self.wTree.get_widget("entry21")
>>  
>> I have had a go at writing a loop for the above 30 textentry boxes.
>> It is below, but it does not work.  
>>  
>> for x in range(20,51):
>> ent = "entry%s" % (str(x))
>>
>> text_x = self.wTree.get_widget(ent)
>>  
>> Is it possible to do what I want it to do?  
>
> NO.  You are looking to create local variables "on the fly".  But there
> is a simple solution that accomplishes what you really want.

The "no" is not absolutely right IMO.  He could write directly in the
dictionary he gets when he calls locals() (but I think you're right in
saying that this is only seldom a good idea).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops to assign variables

2006-07-22 Thread Python
On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
> Hi,
>  
> I am refactoring my code.  I am trying to reduce the amount of lines
> by using more loops.  I tend to use copy and paste a lot instead of
> writing a loop to do the work.
>  
> For example, I have 30 textentry boxes numbered from entry20 to
> entry50.
> I have used the following code to assign the entryboxes to a local
> name.
>  
> text20 = self.wTree.get_widget("entry20")
> text21 = self.wTree.get_widget("entry21")
>  
> I have had a go at writing a loop for the above 30 textentry boxes.
> It is below, but it does not work.  
>  
> for x in range(20,51):
> ent = "entry%s" % (str(x))
>
> text_x = self.wTree.get_widget(ent)
>  
> Is it possible to do what I want it to do?  

NO.  You are looking to create local variables "on the fly".  But there
is a simple solution that accomplishes what you really want.

> Am I on the right lines?

Rather than use local variables, create a container to hold the entry
values.  Then access the entry values from the container.

One container to consider is a dictionary.  It allows you to retrieve
values using fairly arbitrary keys.  Rewriting your loop from above,

text = {}   # create dictionary
for x in range(20,51):
ent = "entry%s" % (x)   # removed unnecessary str(x)
text[x] = self.wTree.get_widget(ent)

Now you can retrieve the values from text using the numbers.  So rather
than text_x, you will code text[x] (or text[20], etc.).

> Any help or advice would be greatly appreciated.

(For program snippets and the kind of content on this list, HTML often
gets in the way.  My email program (Evolution) rendered your email in a
tiny, illegible font.  Turning off HTML would be helpful.)

>  
> Thanks,
>  
> John.
-- 
Lloyd Kvam
Venix Corp

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


[Tutor] loops to assign variables

2006-07-22 Thread John CORRY








Hi,

 

I am refactoring my code.  I am trying to reduce the amount of lines
by using more loops.  I tend to use
copy and paste a lot instead of writing a loop to do the work.

 

For example, I have 30 textentry
boxes numbered from entry20 to entry50. 
I have used the following code to assign the entryboxes
to a local name.

 

text20 = self.wTree.get_widget("entry20")

text21 = self.wTree.get_widget("entry21")

 

I have had a go at writing a loop for the above 30 textentry boxes. 
It is below, but it does not work. 


 

for x in
range(20,51):

   
ent = "entry%s" % (str(x))

   
   

   
text_x = self.wTree.get_widget(ent)

 

Is it possible to do what I want it to do?  Am I on the right lines?  Any help or advice would be greatly
appreciated.

 

Thanks,

 

John.






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