[issue29173] Python 3.6 on Windows wastes a lot of CPU cycles in a while loop

2017-01-05 Thread STINNER Victor

STINNER Victor added the comment:

The code doesn't seem like a bug in Python, but more a classic inefficient busy 
loop pattern. Your loop doesn't sleep and so eats all the CPU.

I suggest to close the issue and ask Python questions on a place to ask 
questions, not on the Python *bug tracker*.

--
nosy: +haypo

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue29173] Python 3.6 on Windows wastes a lot of CPU cycles in a while loop

2017-01-05 Thread Prahlad Yeri

New submission from Prahlad Yeri:

I'm running Python 3.6 on Windows 7. It wastes a lot of cpu cycles when inside 
a loop. In attached screenshot, you'll find that ~25% cpu is used by Python, 
while all I'm doing is running a pomodoro script that waits for a specific 
timeslot to complete. Here is the code for pomodoro.py that runs the while loop 
inside start_tracking() function:

https://github.com/prahladyeri/PyPomodoro/blob/master/pomodoro.py



def start_tracking(task):
global last_beep
print("Working on %s:%s (%d minutes)." % (task['category'], 
task['name'], task['duration']))
print("Started tracking at %s." % 
(datetime.datetime.now().strftime("%H:%M")))
print("Beep interval is set to %d minutes." % config.slot_interval)
session_start_time = datetime.datetime.now()
task_end_time = session_start_time + 
datetime.timedelta(minutes=task['duration'])
last_beep = datetime.datetime.now()
notified = False
while(True):
now = datetime.datetime.now()
diff = (now - last_beep).total_seconds() / 60.0 #in minutes
minutes_worked = round(diff)
reminder_text = "%s:%s" % (task['category'], task['name'])
#diff = diff.total_seconds() / (60.0) 
if (diff >= config.slot_interval): #30
#notify

--
components: Windows
files: Python_high_CPU_Windows.png
messages: 284787
nosy: paul.moore, prahladyeri, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: Python 3.6 on Windows wastes a lot of CPU cycles in a while loop
type: resource usage
versions: Python 3.6
Added file: http://bugs.python.org/file46169/Python_high_CPU_Windows.png

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue29173>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Python while loop

2016-11-30 Thread John Gordon
In <0c642381-4dd2-48c5-bb22-b38f2d5b2...@googlegroups.com> 
paul.garcia2...@gmail.com writes:

> Write a program which prints the sum of numbers from 1 to 101
> (1 and 101 are included) that are divisible by 5 (Use while loop)

> x=0
> count=0
> while x<=100:
> if x%5==0:
> count=count+x
> x=x+1
> print(count)
> 

> Question: How does python know what count means?

"count" is an english word meaning "how many things do I have?", but python
doesn't know that.  In python, "count" is just a name; you could have
called it "hamburger" and python would treat it just the same.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python while loop

2016-11-29 Thread BartC

On 29/11/2016 23:58, paul.garcia2...@gmail.com wrote:

Write a program which prints the sum of numbers from 1 to 101 ( 1 and 101 are 
included) that are divisible by 5 (Use while loop)

This is the code:

x=0
count=0
while x<=100:
if x%5==0:
count=count+x
x=x+1
print(count)


This looks at numbers from 0 to 100 inclusive, not 1 to 101. Although it 
doesn't affect the result. (It will add in 0 which is divisible by 5, 
but that doesn't change it either. If this is an exercise however, 
checking the correct range might be important!)


--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python while loop

2016-11-29 Thread MRAB

On 2016-11-29 23:58, paul.garcia2...@gmail.com wrote:

Write a program which prints the sum of numbers from 1 to 101 ( 1 and 101 are 
included) that are divisible by 5 (Use while loop)

This is the code:

x=0
count=0
while x<=100:
if x%5==0:
count=count+x
x=x+1
print(count)


Question: How does python know what count means ? I see that its declared. What i wanna 
know is how does it know the iteration or each number it finds divisible by 5 is the 
"Count" ??


It doesn't, it's just a name, and, anyway, in the code, 'x' is the count...

If it _did_ know (which is doesn't), wouldn't it be complaining that 
'count' isn't the count but the sum? :-)


--
https://mail.python.org/mailman/listinfo/python-list


Python while loop

2016-11-29 Thread paul . garcia2345
Write a program which prints the sum of numbers from 1 to 101 ( 1 and 101 are 
included) that are divisible by 5 (Use while loop)

This is the code: 

x=0
count=0
while x<=100:
if x%5==0:
count=count+x
x=x+1
print(count)


Question: How does python know what count means ? I see that its declared. What 
i wanna know is how does it know the iteration or each number it finds 
divisible by 5 is the "Count" ??
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-10-27 Thread Veek M
Elizabeth Weiss wrote:

> words=["hello", "world", "spam", "eggs"]
> counter=0
> max_index=len(words)-1
> 
> while counter<=max_index:
> word=words[counter]
> print(word + "!")
> counter=counter + 1


while 0 < 10:
  get 0'th element
  do something with element
  increment 0 to 1
(repeat)


words[0] gets the 0'th word (arrays/lists start at 0, not 1)


That example of his is badly presented..

1. use i, x, y, z, count in that order for integers
2. do your dirty work in a function
3. keep loops clean and tidy
4. keep data far away from code
5. avoid " when ' does the trick
6. try to create black box functions - that work no matter what you 
throw at them.. without sacrificing readability - programming is about 
aesthetics and readability - quite artsy..

(I'm not an expert so.. some of this might be outright wrong)

words=['hello', 'world', 'spam', 'eggs']

def display(txt, decoration='!'):
  message = str(txt) + str(decoration)
  print(message)

i = 0
i_max = len(words) - 1

while i <= i_max:
  word = words[i]
  i += 1
  display(word)

languages that don't have 'for' like C, will use 'while' - in python 
'for' is preferred - faster, readable - especially for the example you 
cited.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop (Reposting On Python-List Prohibited)

2016-10-12 Thread BartC

On 12/10/2016 11:15, Peter Otten wrote:

BartC wrote:


On 12/10/2016 05:30, Lawrence D’Oliveiro wrote:

On Wednesday, October 12, 2016 at 11:23:48 AM UTC+13, BartC wrote:

while n>=x:
 n=n-1
 print "*"* n
else:
 print ("2nd loop exit n=",n,"x=",x)


What is the difference between that and

while n>=x:
 n=n-1
 print "*"* n
print ("2nd loop exit n=",n,"x=",x)

?

None at all.



Not so much in this specific example: that message will be shown whether
there have been 0 or more iterations of the loop body.

But with 'else', if you see the message it means the while statement has
been entered. Here:

if cond:
  while n>=x:
   n=n-1
   print "*"* n
  else:
   print ("2nd loop exit n=",n,"x=",x)


Lawrence is right. The enclosing if doesn't make a difference.


The idea is to detect whether the while loop has been entered.

With while-else-print, it will always execute the else (assuming no 
break). With while then print, you can't tell if it has attempted to or 
not. My example above has wrapped the if-cond around the whole of 
while-else because it has to (that's the advantage).


With a separate print it need not do that:

 if cond:
while n>=x:
   n=n-1
   print "*"* n
 print ("2nd loop exit n=",n,"x=",x)

With real code it may not be as easy to see. 'else' adds structure.

--
bartc
--
https://mail.python.org/mailman/listinfo/python-list


Re: while loop (Reposting On Python-List Prohibited)

2016-10-12 Thread Peter Otten
BartC wrote:

> On 12/10/2016 05:30, Lawrence D’Oliveiro wrote:
>> On Wednesday, October 12, 2016 at 11:23:48 AM UTC+13, BartC wrote:
>>> while n>=x:
>>>  n=n-1
>>>  print "*"* n
>>> else:
>>>  print ("2nd loop exit n=",n,"x=",x)
>>
>> What is the difference between that and
>>
>> while n>=x:
>>  n=n-1
>>  print "*"* n
>> print ("2nd loop exit n=",n,"x=",x)
>>
>> ?
>>
>> None at all.
>>
> 
> Not so much in this specific example: that message will be shown whether
> there have been 0 or more iterations of the loop body.
> 
> But with 'else', if you see the message it means the while statement has
> been entered. Here:
> 
> if cond:
>   while n>=x:
>n=n-1
>print "*"* n
>   else:
>print ("2nd loop exit n=",n,"x=",x)

Lawrence is right. The enclosing if doesn't make a difference.
 
> when cond is false, nothing will be printed. You then know the while
> statement hasn't been entered, so it's not looping for some other reason
> than its loop condition being false from the start.
> 
> Another situation is when the loop body contains 'break'; then it will
> bypass the 'else' part.

This is the only case where while...else makes sense: the code in the else 
suite is executed if and only if the break was not reached.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop (Reposting On Python-List Prohibited)

2016-10-12 Thread BartC

On 12/10/2016 05:30, Lawrence D’Oliveiro wrote:

On Wednesday, October 12, 2016 at 11:23:48 AM UTC+13, BartC wrote:

while n>=x:
 n=n-1
 print "*"* n
else:
 print ("2nd loop exit n=",n,"x=",x)


What is the difference between that and

while n>=x:
 n=n-1
 print "*"* n
print ("2nd loop exit n=",n,"x=",x)

?

None at all.



Not so much in this specific example: that message will be shown whether 
there have been 0 or more iterations of the loop body.


But with 'else', if you see the message it means the while statement has 
been entered. Here:


if cond:
 while n>=x:
  n=n-1
  print "*"* n
 else:
  print ("2nd loop exit n=",n,"x=",x)

when cond is false, nothing will be printed. You then know the while 
statement hasn't been entered, so it's not looping for some other reason 
than its loop condition being false from the start.


Another situation is when the loop body contains 'break'; then it will 
bypass the 'else' part.


--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Re: while loop (Reposting On Python-List Prohibited)

2016-10-11 Thread BartC

On 11/10/2016 22:26, Lawrence D’Oliveiro wrote:

On Wednesday, October 12, 2016 at 6:58:46 AM UTC+13, dhawan...@gmail.com wrote:

Only first loop is executing not the second one?


n=6
x=1
while x<=n:
print("*"*x)
x+=1
print('n=', n)
print('x=', x)
while n>=x:
n=n-1
print("*"* n)

*
**
***

*
**
n= 6
x= 7

Moral: always use debug print statements to figure out what is going on.



'else' can be used here:

n=6
x=1
while x<=n:
print "*"*x
x+=1

while n>=x:
n=n-1
print "*"* n
else:
print ("2nd loop exit n=",n,"x=",x)

--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Re: while loop

2016-10-11 Thread Jussi Piitulainen
dhawanpawa...@gmail.com writes:

> n=6
> x=1
> while x<=n:
> print "*"*x
> x+=1
> while n>=x:
> n=n-1
> print "*"* n
>
>   
> Only first loop is executing not the second one?

It's a basic fact about while loops that after the loop the condition is
false. The two conditions x <= n and n >= x are equivalent.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop

2016-10-11 Thread Michael Torrie
On 10/11/2016 11:58 AM, dhawanpawa...@gmail.com wrote:
> 
> n=6
> x=1
> while x<=n:
> print "*"*x
> x+=1
> while n>=x:
> n=n-1
> print "*"* n
> 
>   
> Only first loop is executing not the second one?

Did you try printing out the loop variable to see what it does and what
it is after the loop is finished?

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop

2016-10-11 Thread Larry Martell
On Tue, Oct 11, 2016 at 1:58 PM,   wrote:
>
> n=6
> x=1
> while x<=n:
> print "*"*x
> x+=1
> while n>=x:
> n=n-1
> print "*"* n
>
>
> Only first loop is executing not the second one?

Because after the first loop n < x
-- 
https://mail.python.org/mailman/listinfo/python-list


while loop

2016-10-11 Thread dhawanpawan32

n=6
x=1
while x<=n:
print "*"*x
x+=1
while n>=x:
n=n-1
print "*"* n

  
Only first loop is executing not the second one?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error in while loop code for packing items

2016-08-18 Thread MRAB

On 2016-08-18 14:10, GP wrote:

On Thursday, August 18, 2016 at 5:59:43 PM UTC+5:30, Peter Otten wrote:

GP wrote:


[snip]


However, when you really want to remove all items you instead assign a new
empty list

for item in items:
print(item)
items = []



Thanks Peter for the information. It helps to find the source of error .

What I wanted was to remove the items that was packed so that the code  can 
check for the next items that match the criteria and then pack those and delete 
them  and keep on repeating until all the items are packed. This is where I am 
getting stuck.

The simplest way is to iterate over the list of items and, for each 
item, if it fits the shelf, put it on the shelf, else put it into a list 
of the 'unused' items.


At the end of a pass, you'll have a shelf of items and a list of the 
remaining items.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Error in while loop code for packing items

2016-08-18 Thread GP
On Thursday, August 18, 2016 at 5:59:43 PM UTC+5:30, Peter Otten wrote:
> GP wrote:
> 
> The error and your second snippet aren't compatible, so I assume the 
> exception is raised by
> 
> > for k in range(0,len(shelf)):
> >   q1=ListDictItem[k]
> >   q2 = ListDictItem.pop(k) #deletes the items that are packed.
> 
> > Error message:Traceback (most recent call last):
> >   File "C:\Project\Python\ReadExcel-xlrd.py", line 201, in 
> > q1=ListDictItem[k]
> > IndexError: list index out of range.
> 
> Take a moment to understand what happens if you iterate over the loop index 
> like above:
> 
> items = ["foo", "bar", "baz"]
> 
> for k in range(len(items)):
> item = items[k]
> print(item)
> items.pop(k)
> 
> You start with k=0, item is set to items[0], i. e. "foo", that is printed 
> and then items.pop(0) removes "foo" from the list which now looks like
> 
> items = ["bar", "baz"]
> 
> Now k=1, item is set to items[1], ie. "baz" ("bar" is never processed), 
> "baz" is printed and then items.pop(1) removes "baz" and the list becomes
> 
> items = ["bar"]
> 
> Now k=2, so when you access items[2] from a list with only one item you get 
> the IndexError. To make similar code work you need a while loop:
> 
> while items:
> item = items.pop(0)
> print(item)
> 
> However, when you really want to remove all items you instead assign a new 
> empty list
> 
> for item in items:
> print(item)
> items = []


Thanks Peter for the information. It helps to find the source of error .

What I wanted was to remove the items that was packed so that the code  can 
check for the next items that match the criteria and then pack those and delete 
them  and keep on repeating until all the items are packed. This is where I am 
getting stuck.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error in while loop code for packing items

2016-08-18 Thread Peter Otten
GP wrote:

The error and your second snippet aren't compatible, so I assume the 
exception is raised by

> for k in range(0,len(shelf)):
>   q1=ListDictItem[k]
>   q2 = ListDictItem.pop(k) #deletes the items that are packed.

> Error message:Traceback (most recent call last):
>   File "C:\Project\Python\ReadExcel-xlrd.py", line 201, in 
> q1=ListDictItem[k]
> IndexError: list index out of range.

Take a moment to understand what happens if you iterate over the loop index 
like above:

items = ["foo", "bar", "baz"]

for k in range(len(items)):
item = items[k]
print(item)
items.pop(k)

You start with k=0, item is set to items[0], i. e. "foo", that is printed 
and then items.pop(0) removes "foo" from the list which now looks like

items = ["bar", "baz"]

Now k=1, item is set to items[1], ie. "baz" ("bar" is never processed), 
"baz" is printed and then items.pop(1) removes "baz" and the list becomes

items = ["bar"]

Now k=2, so when you access items[2] from a list with only one item you get 
the IndexError. To make similar code work you need a while loop:

while items:
item = items.pop(0)
print(item)

However, when you really want to remove all items you instead assign a new 
empty list

for item in items:
print(item)
items = []



-- 
https://mail.python.org/mailman/listinfo/python-list


Error in while loop code for packing items

2016-08-18 Thread GP



I have a list dictionary of items:
ListDictItem = [ {'Item No': 1,'Weight':610,'Quantity':2},{'Item No': 
2,'Weight':610,'Quantity':2},{'Item No': 3,'Weight':500,'Quantity':2},{'Item 
No': 4,'Weight':484,'Quantity':2},{'Item No': 
5,'Weight':470,'Quantity':2},{'Item No': 6,'Weight':440,'Quantity':2},{'Item 
No': 7,'Weight':440,'Quantity':2},{'Item No': 8,'Weight':400,'Quantity':2}]

I would like to pack the items in shelves such that the total weight of each 
shelf is less than a particular value. 

I have created a list of weights from above like this:
ItemWeigths: [610.0, 610.0, 500.0, 484.0, 470.0, 440.0,440, 400.0]


and a code which creates the first shelf :

shelves=[]
ShelvesWeightTotal = sum(shelves)
shelf=[]
new=[]
ShelfToPack=[]


for i in range(0,len(ItemWeigths)):
while ShelvesWeightTotal <=WeightOfObject:
  shelf += [ItemWeigths[i]]
  ShelvesWeightTotal = sum(shelf)

for k in range(0,len(shelf)):
  q1=ListDictItem[k]
  q2 = ListDictItem.pop(k) #deletes the items that are packed.
  shelves.append(q1)
  new.append(q2)   

ShelfToPack.append(shelves)

This code works but when I try to create other shelves, I made a while 
statement over the items that are remaining ,(while ItemsRemaining !=0) and I 
get an error for the code. The details are below:

Code:

while ListDictItem != []:

   for i in range(0,len(ItemsToCutLength)):
   while ShelvesLengthTotal <=LengthOfObject:
  shelves += [ItemWeigths[i]]
  ShelvesLengthTotal = sum(shelves)

   for k in range(0,len(shelves)):
  q1=ItemsToCut[k]
  q2 = ListDictItemt.pop(k) #deletes the items that are packed.
  shelf.append(q1)
  new.append(q2)   
   ListDictItem==ListDictItem 
ShelfToPack.append(shelf)


Error message:Traceback (most recent call last):
  File "C:\Project\Python\ReadExcel-xlrd.py", line 201, in 
q1=ListDictItem[k]
IndexError: list index out of range.


I would like the ShelfToPack list look like :

[[{'Item No': 1,'Weight':610,'Quantity':2},{'Item No': 
2,'Weight':610,'Quantity':2},{'Item No': 3,'Weight':500,'Quantity':2},{'Item 
No': 4,'Weight':484,'Quantity':2}],[{..},...{..}],[{..},...{..}]]

Any suggestion in pointing the error or to improve the code will be appreciated.

Thanks in advance!! 

Cheers!
GP
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-30 Thread jfong
Steven D'Aprano at 2016/6/30 7:59:40AM wrote:
> py> mi = list('bananas')
> py> for char in mi:
> ... if char == 'a':
> ... mi.extend(' yum')
> ... print(char, end='')
> ... else:  # oh no, the feared for...else!
> ... # needed to prevent the prompt overwriting the output
> ... print()
> ...
> bananas yum yum yum
> py> 
> 
> 
> This example shows two things:
... 
> (2) Anyone who says that for...else without break is useless is wrong.

Haha...you win.

By the way, I never said "else" without "break" is illegal or useless, I said 
it will cause confusion semantically, just like this(it reminds me the IOCCC:-):

import math
pass
import os
pass
import sys 

Think of the "try ...except ...else ..." where the situation is similar but 
luckily it was mandatory.

--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-30 Thread Ian Kelly
On Wed, Jun 29, 2016 at 5:59 PM, Steven D'Aprano  wrote:
> But there's no need to go to such effort for a mutable iterator. This is
> much simpler:
>
> py> mi = list('bananas')
> py> for char in mi:
> ... if char == 'a':
> ... mi.extend(' yum')
> ... print(char, end='')
> ... else:  # oh no, the feared for...else!
> ... # needed to prevent the prompt overwriting the output
> ... print()
> ...
> bananas yum yum yum
> py>

One small difference with this approach is that iterators extended
onto the list are iterated over immediately rather than in sequence.
That could have implications in some scenarios.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-30 Thread Ian Kelly
On Wed, Jun 29, 2016 at 5:59 PM, Steven D'Aprano  wrote:
> I'm curious what REPL you are using, because in the vanilla Python
> interactive interpreter, the output if over-written by the prompt. That is,
> what I see in Python 3.6 is:
>
> py> nas yum yum yumpy>
>
> unless I take steps to prevent that. See below.

I was just using the CPython 3.4 REPL with the default prompt. It
appended the prompt rather than overwriting, and I simply omitted it
in my message since it wasn't relevant to the example.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-30 Thread Tim Chase
On 2016-06-30 09:59, Steven D'Aprano wrote:
> But there's no need to go to such effort for a mutable iterator.
> This is much simpler:
>   
> py> mi = list('bananas')
> py> for char in mi:
> ... if char == 'a':
> ... mi.extend(' yum')
> ... print(char, end='')
> ... else:  # oh no, the feared for...else!
> ... # needed to prevent the prompt overwriting the output
> ... print()
> ...
> bananas yum yum yum  
> py> 
> 
> 
> This example shows two things:
> 
> (1) There's no need for a MutableIterator, we have list;  

Convenient to know.  I was fairly certain that this had failed for me
in past versions, but I went back to the oldest I have (2.4) and it
still works there.  Might have to revisit some queuing code I have.

That said, it's not consistent across iterable container types.  With

  mi = set('bananas')
  for char in mi:
if char == 'a':
  mi.add('X')
print(char)
  else:
print()

I get

  Traceback (most recent call last):
File "", line 1, in 
  RuntimeError: Set changed size during iteration

If the list() meets your needs, then you're in luck.  But just as
frequently, I want to use a set() or a dict() and have to write my
own wrapper around it.

-tkc

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-29 Thread Steven D'Aprano
On Thu, 30 Jun 2016 01:29 am, Ian Kelly wrote:

> On Tue, Jun 28, 2016 at 11:58 AM, Grant Edwards
> <grant.b.edwa...@gmail.com> wrote:
[...]
>>> But then, if you wrap up your "while" loop as a generator that yields
>>> things, you can then use it in a "for" loop which seems to me like
>>> the Pythonic way to do things. :-)
>>
>> Yea, I keep telling myself that, but I never actually do it.
> 
> Here you go:
> 
> import collections
> 
> class MutableIterator:
[snip 8 methods and 33 lines of code]

> # Example:
> 
>>>> mi = MutableIterator('bananas')
>>>> for char in mi:
> ...   if char == 'a':
> ... mi.extend(' yum')
> ...   print(char, end='')
> ...
> bananas yum yum yum

I'm curious what REPL you are using, because in the vanilla Python
interactive interpreter, the output if over-written by the prompt. That is,
what I see in Python 3.6 is:

py> nas yum yum yumpy> 

unless I take steps to prevent that. See below.


But there's no need to go to such effort for a mutable iterator. This is
much simpler:

py> mi = list('bananas')
py> for char in mi:
... if char == 'a':
... mi.extend(' yum')
... print(char, end='')
... else:  # oh no, the feared for...else!
... # needed to prevent the prompt overwriting the output
... print()
...
bananas yum yum yum
py> 


This example shows two things:

(1) There's no need for a MutableIterator, we have list;

(2) Anyone who says that for...else without break is useless is wrong.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-29 Thread Ian Kelly
On Tue, Jun 28, 2016 at 11:58 AM, Grant Edwards
<grant.b.edwa...@gmail.com> wrote:
> On 2016-06-28, Tim Chase <python.l...@tim.thechases.com> wrote:
>> On 2016-06-29 01:20, Steven D'Aprano wrote:
>>> While loops are great for loops where you don't know how many
>>> iterations there will be but you do know that you want to keep
>>> going while some condition applies:
>>>
>>> while there is still work to be done:
>>> do some more work
>>
>> I find this particularly the case when the thing being iterated over
>> can be changed, such as a queue of things to process:
>>
>>   items = deque()
>>   items.append(root_node)
>>   while items:
>> item = items.popleft()
>> process(item)
>> items.extend(item.children)
>
> Yep, I often do something similar when processing a block of data
> bytes comprising a sequence of "things" of varying number of bytes.
>
> data = read_a_blob_of_bytes()
> while data:
>     #figure out how long the first "thing" is
> len =  'data'>
> handle_thing(data[:len])
> data = data[len:]
>> But then, if you wrap up your "while" loop as a generator that yields
>> things, you can then use it in a "for" loop which seems to me like
>> the Pythonic way to do things. :-)
>
> Yea, I keep telling myself that, but I never actually do it.

Here you go:

import collections

class MutableIterator:

  def __init__(self, iterable):
self._stopped = False
self.replace(iterable)

  def __iter__(self):
return self

  def __next__(self):
if self._stopped:
  raise StopIteration
while self._iterator or self._iterables:
  if self._iterator:
try:
  return next(self._iterator)
except StopIteration:
  self._iterator = None
  if self._iterables:
self._iterator = iter(self._iterables.popleft())
self._stopped = True
raise StopIteration

  def clear():
self._iterables.clear()
self._iterator = None

  def replace(self, iterable):
self._check_stopped()
self._iterables = collections.deque([iterable])
self._iterator = None

  def append(self, item):
self.extend([item])

  def extend(self, iterable):
self._check_stopped()
self._iterables.append(iterable)

  def _check_stopped(self):
if self._stopped:
  raise ValueError('Tried to mutate a stopped iterator')


# Example:

>>> mi = MutableIterator('bananas')
>>> for char in mi:
...   if char == 'a':
... mi.extend(' yum')
...   print(char, end='')
...
bananas yum yum yum
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-29 Thread Lawrence D’Oliveiro
On Wednesday, June 29, 2016 at 1:30:04 AM UTC+12, BartC wrote:
> I don't know if that helps; I've never heard of an induction variable. 

Perhaps it’s just a computability-theoretic way of saying “a variable whose 
value each time round the loop is a function of its value on the previous 
iteration”.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Grant Edwards
On 2016-06-28, Tim Chase <python.l...@tim.thechases.com> wrote:
> On 2016-06-29 01:20, Steven D'Aprano wrote:
>> While loops are great for loops where you don't know how many
>> iterations there will be but you do know that you want to keep
>> going while some condition applies:
>> 
>> while there is still work to be done:
>> do some more work
>
> I find this particularly the case when the thing being iterated over
> can be changed, such as a queue of things to process:
>
>   items = deque()
>   items.append(root_node)
>   while items:
> item = items.popleft()
> process(item)
> items.extend(item.children)

Yep, I often do something similar when processing a block of data
bytes comprising a sequence of "things" of varying number of bytes.

data = read_a_blob_of_bytes()
while data:
#figure out how long the first "thing" is
len =   
    handle_thing(data[:len])
data = data[len:]
> But then, if you wrap up your "while" loop as a generator that yields
> things, you can then use it in a "for" loop which seems to me like
> the Pythonic way to do things. :-)

Yea, I keep telling myself that, but I never actually do it.

-- 
Grant Edwards   grant.b.edwardsYow! How do I get HOME?
  at   
  gmail.com

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Tim Chase
On 2016-06-29 01:20, Steven D'Aprano wrote:
> While loops are great for loops where you don't know how many
> iterations there will be but you do know that you want to keep
> going while some condition applies:
> 
> while there is still work to be done:
> do some more work

I find this particularly the case when the thing being iterated over
can be changed, such as a queue of things to process:

  items = deque()
  items.append(root_node)
  while items:
item = items.popleft()
process(item)
items.extend(item.children)

Using a "for" loop balks if you try to change the thing over which
you're iterating.

But then, if you wrap up your "while" loop as a generator that yields
things, you can then use it in a "for" loop which seems to me like
the Pythonic way to do things. :-)

-tkc



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Jussi Piitulainen
Steven D'Aprano writes:

> While loops are great for loops

:)

Thanks, I needed the laugh.

> where you don't know how many iterations there will be but you do know
> that you want to keep going while some condition applies:

(Just keeping a bit of context so it doesn't seem like I'm laughing at
the intended reading.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Steven D'Aprano
On Tue, 28 Jun 2016 10:36 pm, Elizabeth Weiss wrote:

> Why do we use this code if we can use the simpler for loop?

Nobody with any sense would use the more complex while loop when the for
loop does the same thing.

While loops are great for loops where you don't know how many iterations
there will be but you do know that you want to keep going while some
condition applies:

while there is still work to be done:
do some more work


But if you know how many iterations there will be, use the for loop. Even if
you don't know the number ahead of time, if you have a list of them, use a
for loop:

for each job on my todo list:
do the job



There is a fashion, driven by "Learn Python The Hard Way", to teach people
the while loop first, because it's hard. I think that is stupid. It's like
teaching people to fly the Space Shuttle first, then saying "Ok, the Space
Shuttle is really complicated, but you can ride a bicycle instead" and then
teach them to ride a pushbike.





-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Michael Selik
On Tue, Jun 28, 2016 at 9:26 AM Joseph Lee <joseph.lee22...@gmail.com>
wrote:

>
> -Original Message-
> From: Michael Selik
> Sent: Tuesday, June 28, 2016 6:16 AM
>
> MS: You should not. Use the first version, it's much better. Python
> for-loops are preferable to while-loops.
>
> JL: For the most part, for loops are better, but there are times when
> while loops are preferable such as when you don't know the size of the
> input beforehand.


Not knowing the number of elements is not a reason to prefer a while-loop.
A for-loop handles that quite well.

with open('example.txt') as f:
for line in f:
print(line)

We often loop over files without knowing how big a file is.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Michael Selik
On Tue, Jun 28, 2016 at 9:34 AM BartC  wrote:

> On 28/06/2016 14:15, Michael Selik wrote:
> > On Tue, Jun 28, 2016 at 8:41 AM Elizabeth Weiss 
> wrote:
> >
> >> I do not understand the second code. What is counter?
> >>
> >
> > It looks like someone wanted to make a loop induction variable.
> > https://en.wikipedia.org/wiki/Induction_variable
>
> I don't know if that helps; I've never heard of an induction variable.
>

But you've seen them often in other programming languages?


> And according to the first example in that link, then 'word' in the OP's
> second example might be classed as an induction variable too!


The variable ``word`` was not being incremented/decremented by a fixed
amount, nor was it a linear function of another induction variable.


> Confusing.


Indeed. That's why Python's for-loops are preferable.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Jussi Piitulainen
Elizabeth Weiss writes:

[- -]

> What I do not understand is:
>
> words=["hello", "world", "spam", "eggs"]
> counter=0
> max_index=len(words)-1
>
> while counter<=max_index:
>word=words[counter]
>print(word + "!")
>counter=counter + 1

# make it so that counter == 0
counter=0

# make it so that max_index is the greatest valid index to words (unless
# words is empty -- it would be simpler and idiomatic to make end_index
# be the first invalid index aka len(words), but make your life that
# little bit harder because ... reasons?)
max_index=len(words)-1

while counter<=max_index:

# Since we reached this point, counter is at most max_index, and is
# a valid index unless words is empty. If the test was instead
# counter < end_index, it would definitely be valid, or we wouldn't
# be *here*. Anyway, the first time at this point, counter == 0, the
# second time counter == 1, ...

# Set word to the item of words indicated by counter. First time at
# this point, words[0], second time, words[1], ...; print it.
word=words[counter]
print(word + "!")

# Make it so that counter is one larger than it used to be. In
# particular, it is closer to being larger than max_index so that we
# are eventually done with this loop.
counter=counter + 1

# At this point, the loop condition is tested again with the new
# value of counter(*) and when that new value is such it is no
# longer the case that counter<=max_index, looping ends.

# When we reach this point, the loop condition is false (or there has
# been another kind of exit from the loop): counter == max_index + 1.

(*) Now the thread may go into yet another tangent on how that "new
value" is really not a value but is the value of an immutable object
that is the value of a reference pointer in a box that is tied to a
puppy that is dancing on the point of a pin. You may or may not find
that helpful. Also, one or more of these things may be a name or have a
name.

> Both of these result in the same answer. 
> I do not understand the second code. What is counter?
> Why do we use this code if we can use the simpler for loop? 

Some loops are not easily written as for loops. This is not one of them.

For loops are easy to rewrite as while loops, so while loops may be
considered theoretically more fundamental. Other theoretical models
would express while loops with even more fundamental mechanisms (or they
can be quite practical models, though not directly available in Python
for this purpose or at all: conditional jumps to a labelled region of
program code, or function calls).

You need to get used to how program elements like counter behave. There
are events in the execution of a program that make it so that such
program elements stand for particular things (like numbers) in a
dependable way, in certain specific regions of code, until some new
event. The statement involving a single equals sign is one such event;
each entry to a for loop is another; a function call is yet another.

(I see that I have used the word "thing" about things that I really do
think of as things in the context of a Python program, and of things
that I don't. [REDACTED] it's hard to talk about these, er, things.
Please ignore this paragraph, and that paragraph marked with (*).)

[- -]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread BartC

On 28/06/2016 14:15, Michael Selik wrote:

On Tue, Jun 28, 2016 at 8:41 AM Elizabeth Weiss  wrote:


I do not understand the second code. What is counter?



It looks like someone wanted to make a loop induction variable.
https://en.wikipedia.org/wiki/Induction_variable


I don't know if that helps; I've never heard of an induction variable. 
And according to the first example in that link, then 'word' in the OP's 
second example might be classed as an induction variable too! Confusing.


--
Bartc

--
https://mail.python.org/mailman/listinfo/python-list


RE: Iteration, while loop, and for loop

2016-06-28 Thread Joseph Lee
Hi,
Answers inline.

-Original Message-
From: Python-list
[mailto:python-list-bounces+joseph.lee22590=gmail@python.org] On Behalf
Of Michael Selik
Sent: Tuesday, June 28, 2016 6:16 AM
To: Elizabeth Weiss <cake...@gmail.com>; python-list@python.org
Subject: Re: Iteration, while loop, and for loop

On Tue, Jun 28, 2016 at 8:41 AM Elizabeth Weiss <cake...@gmail.com> wrote:

> I do not understand the second code. What is counter?
>

It looks like someone wanted to make a loop induction variable.
https://en.wikipedia.org/wiki/Induction_variable

JL: Or access the array item via indexing.

> Why do we use this code if we can use the simpler for loop?
>

You should not. Use the first version, it's much better. Python for-loops
are preferable to while-loops.

JL: Indexing is useful if one wishes to assign something different to the
position represented by container[index]. But if you want a more elegant way
to access the actual object in question, then using the first fragment is
better (and more readable). For the most part, for loops are better, but
there are times when while loops are preferable such as when you don't know
the size of the input beforehand.

Cheers,
Joseph

-
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread BartC

On 28/06/2016 13:36, Elizabeth Weiss wrote:

I understand this code:

words=["hello", "world", "spam", "eggs"]
for words in words
   print(word + "!")

What I do not understand is:

words=["hello", "world", "spam", "eggs"]
counter=0
max_index=len(words)-1

while counter<=max_index:
   word=words[counter]
   print(word + "!")
   counter=counter + 1



Both of these result in the same answer.
I do not understand the second code. What is counter?
Why do we use this code if we can use the simpler for loop?

If you could please explain the second code step by step that would be great!


Imagine the words are printed in a book, one per page, and the pages are 
numbered 0, 1, 2 and 3 (starting from 0 as is the perverse say of many 
programming languages).


len(words)-1 is the number of pages in the book (4) less one to account 
for the odd numbering. Max_index is then the number of the last page (3).


Counter then goes through the pages one by one, starting at page 0 and 
ending at page 3 (ie. max_index), reading the word on each and printing 
it out with "!" appended.


However, because the language is zero-based, this would have been better 
written as:


 num_words = len(words)

 while counter < num_words:  # or just while counter < len(words)

That's if you had to write it as while loop. With the for=loop version, 
these details are taken care of behind the scenes.


--
Bartc

--
https://mail.python.org/mailman/listinfo/python-list


Re: Iteration, while loop, and for loop

2016-06-28 Thread Michael Selik
On Tue, Jun 28, 2016 at 8:41 AM Elizabeth Weiss  wrote:

> I do not understand the second code. What is counter?
>

It looks like someone wanted to make a loop induction variable.
https://en.wikipedia.org/wiki/Induction_variable


> Why do we use this code if we can use the simpler for loop?
>

You should not. Use the first version, it's much better. Python for-loops
are preferable to while-loops.
-- 
https://mail.python.org/mailman/listinfo/python-list


Iteration, while loop, and for loop

2016-06-28 Thread Elizabeth Weiss
I understand this code:

words=["hello", "world", "spam", "eggs"]
for words in words
   print(word + "!")

What I do not understand is:

words=["hello", "world", "spam", "eggs"]
counter=0
max_index=len(words)-1

while counter<=max_index:
   word=words[counter]
   print(word + "!")
   counter=counter + 1



Both of these result in the same answer. 
I do not understand the second code. What is counter?
Why do we use this code if we can use the simpler for loop? 

If you could please explain the second code step by step that would be great!

Thank you!!!
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue22719] os.path.isfile os.path.exists bug in while loop

2014-11-10 Thread Aaron

Aaron added the comment:

Python 3.3.0, Windows 7, both 64 bit.

Has it been resolved with the newer version, then?

On Mon, Nov 3, 2014 at 11:15 PM, Zachary Ware rep...@bugs.python.org
wrote:


 Zachary Ware added the comment:

 Aaron, what version of Python are you using on what version of Windows?
 Also, 32 or 64 bit on both?

 I can't reproduce this with any Python 3.3.6 or newer on 64-bit Windows
 8.1.

 --

 ___
 Python tracker rep...@bugs.python.org
 http://bugs.python.org/issue22719
 ___


--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-11-10 Thread Zachary Ware

Zachary Ware added the comment:

I haven't built 3.3.0 again yet to try to reproduce with it, but there
have been enough bug and security fixes in the more recent 3.3
releases that I'd strongly advise updating on general principle and
seeing if this issue goes away.  If not to 3.4.2, at least to 3.3.5
(the last 3.3 version to have a Windows installer).

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-11-10 Thread Zachary Ware

Zachary Ware added the comment:

I have had a chance to build 3.3.0 and I was able to reproduce the bug with it, 
so it is in fact fixed in later versions.

--
resolution:  - out of date
stage:  - resolved
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-11-03 Thread Zachary Ware

Zachary Ware added the comment:

Aaron, what version of Python are you using on what version of Windows?  Also, 
32 or 64 bit on both?

I can't reproduce this with any Python 3.3.6 or newer on 64-bit Windows 8.1.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists but in while loop

2014-10-24 Thread Aaron

New submission from Aaron:

When using os.path.isfile() and os.path.exists() in a while loop under certain 
conditions, os.path.isfile() returns True for paths that do not actually exist.

Conditions:
The folder C:\Users\EAARHOS\Desktop\Python Review exists, as do the files 
C:\Users\EAARHOS\Desktop\Python Review\baseExcel.py and 
C:\Users\EAARHOS\Desktop\Python Review\baseExcel.py.bak. (Note that I also 
tested this on a path that contained no spaces, and got the same results.)

Code:
 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 while os.path.isfile(bak_path):
... bak_path += '.bak'
... if not os.path.isfile(bak_path):
... break
Traceback (most recent call last):
  File interactive input, line 3, in module
  File C:\Installs\Python33\Lib\genericpath.py, line 29, in isfile
st = os.stat(path)
ValueError: path too long for Windows
 os.path.isfile(rC:\Users\EAARHOS\Desktop\Python 
 Review\baseExcel.py.bak.bak)
False
 

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 while os.path.exists(bak_path):
... bak_path += '.bak'
... if not os.path.exists(bak_path):
... break
Traceback (most recent call last):
  File interactive input, line 3, in module
  File C:\Installs\Python33\Lib\genericpath.py, line 18, in exists
st = os.stat(path)
ValueError: path too long for Windows
 os.path.exists(rC:\Users\EAARHOS\Desktop\Python 
 Review\baseExcel.py.bak.bak)
False
 

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 os.path.isfile(bak_path), os.path.exists(bak_path)
(True, True)
 bak_path += '.bak'
 os.path.isfile(bak_path), os.path.exists(bak_path)
(True, True)
 bak_path += '.bak'
 os.path.isfile(bak_path), os.path.exists(bak_path)
(True, True)
 bak_path
'C:\\Users\\EAARHOS\\Desktop\\Python Review\\baseExcel.py.bak.bak'
 temp = bak_path
 os.path.isfile(temp), os.path.exists(temp)
(True, True)
 os.path.isfile('C:\\Users\\EAARHOS\\Desktop\\Python 
 Review\\baseExcel.py.bak.bak'), 
 os.path.exists('C:\\Users\\EAARHOS\\Desktop\\Python 
 Review\\baseExcel.py.bak.bak')
(False, False)
 

On the other hand, this code works as expected:

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 while os.path.isfile(bak_path):
... temp = bak_path + '.bak'
... bak_path = temp
... 
 bak_path
'C:\\Users\\EAARHOS\\Desktop\\Python Review\\baseExcel.py.bak.bak'
 

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 while os.path.exists(bak_path):
... temp = bak_path + '.bak'
... bak_path = temp
... 
 bak_path
'C:\\Users\\EAARHOS\\Desktop\\Python Review\\baseExcel.py.bak.bak'


--
components: Windows
messages: 229936
nosy: hosford42, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: os.path.isfile  os.path.exists but in while loop
type: behavior
versions: Python 3.3

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread Aaron

Changes by Aaron hosfor...@gmail.com:


--
title: os.path.isfile  os.path.exists but in while loop - os.path.isfile  
os.path.exists bug in while loop

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread R. David Murray

R. David Murray added the comment:

Interesting bug.  The obvious difference between the two cases is that in the 
+= version the address of the string pointing to the filepath doesn't change, 
whereas when you use a temp variable it does (there's an optimization in += 
that reuses the same memory location if possible).  It looks like something is 
seeing that repeated addresses and returning the same result as the last time 
that address was passed, which is wrong.

I don't see anything obvious in os module.  Although I can't rule out a Python 
bug, since this works fine on unix I suspect this is a Windows CRT bug.

--
nosy: +r.david.murray

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread Steve Dower

Steve Dower added the comment:

I wonder whether the same thing occurs if you're not appending a new extension 
each time? There could be some optimisation (from the dark old days of 8.3 
filename) that compares baseExcel and .bak separately and assumes that the 
name is known.

Last I looked at the code for stat() and isfile(), it was going directly to the 
Win32 API and not via the CRT. Though that may not have been the case in 3.3...

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Could we encode both paths to the unicode_internal encoding and check if 
results are equal?

--
nosy: +serhiy.storchaka

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread R. David Murray

R. David Murray added the comment:

Looking at the code, it looks like it calls the win32 api directly if 
path-wide is true, which I'm guessing is the case unless you are using bytes 
paths in windows?  It looks like the critical call, then, is CreateFileA (why A 
in a _w method I have no idea...so my reading of this code is suspect :)

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread eryksun

eryksun added the comment:

What do you get for os.stat?

bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
print(os.stat(bak_path))
bak_path += '.bak'
print(os.stat(bak_path))
bak_path += '.bak'
print(os.stat(bak_path)) # This should raise FileNotFoundError

--
nosy: +eryksun

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread Aaron

Aaron added the comment:

Interesting. It continues to reuse the last one's stats once the path is no
longer valid.

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=8162774324652726, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=29874, st_atime=1413389016,
st_mtime=1413389016, st_ctime=1413388655)
 bak_path += '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 bak_path += '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 bak_path += '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 bak_path += '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)


On Fri, Oct 24, 2014 at 1:49 PM, eryksun rep...@bugs.python.org wrote:


 eryksun added the comment:

 What do you get for os.stat?

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 print(os.stat(bak_path))
 bak_path += '.bak'
 print(os.stat(bak_path))
 bak_path += '.bak'
 print(os.stat(bak_path)) # This should raise FileNotFoundError

 --
 nosy: +eryksun

 ___
 Python tracker rep...@bugs.python.org
 http://bugs.python.org/issue22719
 ___


--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread Aaron

Aaron added the comment:

If I use a separate temp variable, the bug doesn't show, but if I use the
same variable, even with + instead of +=, it still happens.

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=8162774324652726, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=29874, st_atime=1413389016,
st_mtime=1413389016, st_ctime=1413388655)
 temp = bak_path + '.bak'
 bak_path = temp
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 temp = bak_path + '.bak'
 bak_path = temp
 print(os.stat(bak_path))
Traceback (most recent call last):
  File interactive input, line 1, in module
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\Users\\EAARHOS\\Desktop\\Python Review\\baseExcel.py.bak.bak'

 bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
 bak_path = bak_path + '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 bak_path = bak_path + '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 bak_path = bak_path + '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)
 bak_path = bak_path + '.bak'
 print(os.stat(bak_path))
nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
st_mtime=1413389088, st_ctime=1413388654)


On Fri, Oct 24, 2014 at 2:24 PM, Aaron rep...@bugs.python.org wrote:


 Aaron added the comment:

 Interesting. It continues to reuse the last one's stats once the path is no
 longer valid.

  bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
  print(os.stat(bak_path))
 nt.stat_result(st_mode=33206, st_ino=8162774324652726, st_dev=0,
 st_nlink=1, st_uid=0, st_gid=0, st_size=29874, st_atime=1413389016,
 st_mtime=1413389016, st_ctime=1413388655)
  bak_path += '.bak'
  print(os.stat(bak_path))
 nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
 st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
 st_mtime=1413389088, st_ctime=1413388654)
  bak_path += '.bak'
  print(os.stat(bak_path))
 nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
 st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
 st_mtime=1413389088, st_ctime=1413388654)
  bak_path += '.bak'
  print(os.stat(bak_path))
 nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
 st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
 st_mtime=1413389088, st_ctime=1413388654)
  bak_path += '.bak'
  print(os.stat(bak_path))
 nt.stat_result(st_mode=33206, st_ino=42502721483352490, st_dev=0,
 st_nlink=1, st_uid=0, st_gid=0, st_size=2, st_atime=1413389088,
 st_mtime=1413389088, st_ctime=1413388654)
 

 On Fri, Oct 24, 2014 at 1:49 PM, eryksun rep...@bugs.python.org wrote:

 
  eryksun added the comment:
 
  What do you get for os.stat?
 
  bak_path = rC:\Users\EAARHOS\Desktop\Python Review\baseExcel.py
  print(os.stat(bak_path))
  bak_path += '.bak'
  print(os.stat(bak_path))
  bak_path += '.bak'
  print(os.stat(bak_path)) # This should raise FileNotFoundError
 
  --
  nosy: +eryksun
 
  ___
  Python tracker rep...@bugs.python.org
  http://bugs.python.org/issue22719
  ___
 

 --

 ___
 Python tracker rep...@bugs.python.org
 http://bugs.python.org/issue22719
 ___


--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread eryksun

eryksun added the comment:

When appending to a singly-referenced string, the interpreter tries to 
reallocate the string in place. This applies to both `s += 'text'` and `s = s + 
'text'`. Storing to a temp variable is adding a 2nd reference, so a new string 
gets allocated instead. If the former is the case (i.e. the object id is the 
same after appending), use ctypes to check the string's cached wide-string 
(wchar_t *) representation:

from ctypes import *
 
pythonapi.PyUnicode_AsUnicode.argtypes = [py_object]
pythonapi.PyUnicode_AsUnicode.restype = c_wchar_p

print(pythonapi.PyUnicode_AsUnicode(bak_path))

The wstr cache should be cleared when the string is reallocated in place, so 
this is probably a dead end.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22719] os.path.isfile os.path.exists bug in while loop

2014-10-24 Thread eryksun

eryksun added the comment:

 i.e. the object id is the same after appending

Actually, that's wrong. bak_path is a compact string. So the whole object is 
realloc'd, and the base address (i.e. id) could change. Check 
PyUnicode_AsUnicode even if the id changes.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22719
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: while loop - multiple condition

2014-10-14 Thread giacomo boffi
Tim Chase python.l...@tim.thechases.com writes:

 On 2014-10-12 22:16, Marko Rauhamaa wrote:
 is equivalent with
 
 while ans.lower()[0] != 'y':
  ans = input('Do you like python?')

 And still better improved with

   while ans[:1].lower() != 'y':
 ans = input('Do you like python?')

 yok is Turkish for an EMPHATIC NO
(or, at least, that's what I was led to think many years ago)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-14 Thread Chris Angelico
On Wed, Oct 15, 2014 at 10:04 AM, giacomo boffi pec...@pascolo.net wrote:
 Tim Chase python.l...@tim.thechases.com writes:

 On 2014-10-12 22:16, Marko Rauhamaa wrote:
 is equivalent with

 while ans.lower()[0] != 'y':
  ans = input('Do you like python?')

 And still better improved with

   while ans[:1].lower() != 'y':
 ans = input('Do you like python?')

  yok is Turkish for an EMPHATIC NO
 (or, at least, that's what I was led to think many years ago)

Corrupted core, are you ready to start the procedure?
What do you think?
Interpreting vague answer as: Yes!

If your program misinterprets a non-English response to an English
question, that's not critical. It just means you haven't implemented
full i18n. :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Gelonida N

On 10/12/2014 07:08 PM, Shiva wrote:

while ans.lower() != 'yes' or ans.lower()[0] != 'y':
  ans = input('Do you like python?')


I personally consider double negations less intuitive than following:


while not( ans.lower() == 'yes' and ans.lower()[0] == 'y' ):

Reading this line yoy would have noticed as wellm that what you really 
wanted would have been:


while not( ans.lower() == 'yes' or ans.lower()[0] == 'y' ):



I would write the coder differently.

With your code you have to pre-initialze the variable ans.


I personally consider it also more 'intuitive' / easier to understand if
I can see the break conditiion. to many nots  / != / negations can be 
confusing as you noticed yourself.


Taking into account the Steven's suggestion about using the 'in' 
expression it could be:



while True:
ans = input('Do you like python?')
if ans.lower() in ('yes', 'y'):
break






--
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Chris Angelico
On Mon, Oct 13, 2014 at 7:31 PM, Gelonida N gelon...@gmail.com wrote:
 Taking into account the Steven's suggestion about using the 'in' expression
 it could be:


 while True:
 ans = input('Do you like python?')
 if ans.lower() in ('yes', 'y'):
 break

Or, even simpler: Use an active condition.

while input('Do you like python?') not in ('yes', 'y'): pass

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 Or, even simpler: Use an active condition.

 while input('Do you like python?') not in ('yes', 'y'): pass

Instead of the traditional pull technology, you could take advantage
of the state-of-the-art push approach:

   print(You must love python -- everybody does!)


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Skip Montanaro
On Mon, Oct 13, 2014 at 6:59 AM, Chris Angelico ros...@gmail.com wrote:

 while input('Do you like python?') not in ('yes', 'y'): pass


Unfortunately, you probably have to account for people who SHOUT:

while input('Do you like python?').lower() not in ('yes', 'y'): pass

wink

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Chris Angelico
On Mon, Oct 13, 2014 at 11:10 PM, Skip Montanaro
skip.montan...@gmail.com wrote:
 On Mon, Oct 13, 2014 at 6:59 AM, Chris Angelico ros...@gmail.com wrote:

 while input('Do you like python?') not in ('yes', 'y'): pass


 Unfortunately, you probably have to account for people who SHOUT:

 while input('Do you like python?').lower() not in ('yes', 'y'): pass

 wink

Welcome to collaborative editing. I make a change and introduce a bug.
Fortunately, someone else can, just like that, fix that bug. Thanks!
:)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Chris Angelico
On Mon, Oct 13, 2014 at 11:09 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Chris Angelico ros...@gmail.com:

 Or, even simpler: Use an active condition.

 while input('Do you like python?') not in ('yes', 'y'): pass

 Instead of the traditional pull technology, you could take advantage
 of the state-of-the-art push approach:

print(You must love python -- everybody does!)

Nay, there is love in excess. I thank heaven there are many pythons in
England; but if thou lovest them all, I withdraw my thanks!
-- Colonel Fairfax

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Rob Gaddi
On Mon, 13 Oct 2014 09:56:02 +1100
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote:
 
 When you have multiple clauses in the condition, it's easier to reason about
 them if you write the clauses as positive statements rather than negative
 statements, that is, something is true rather than something is not
 true, and then use `not` to reverse it if you want to loop *until* the
 overall condition is true.
 

I was just explaining this concept to a young pup the other day.  De
Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but
the positive logic flavor is substantially less error-prone.  People
are fundamentally not as good at thinking about inverted logic.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Rustom Mody
On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote:
 On Mon, 13 Oct 2014 09:56:02 +1100
 Steven D'Aprano  wrote:
  When you have multiple clauses in the condition, it's easier to reason about
  them if you write the clauses as positive statements rather than negative
  statements, that is, something is true rather than something is not
  true, and then use `not` to reverse it if you want to loop *until* the
  overall condition is true.

 I was just explaining this concept to a young pup the other day.  De
 Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but
 the positive logic flavor is substantially less error-prone.  People
 are fundamentally not as good at thinking about inverted logic.

Curious: Which of

- (not (p and q))
- ((not p) or (not q))

is more positive (less negative)??
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Rob Gaddi
On Mon, 13 Oct 2014 09:26:57 -0700 (PDT)
Rustom Mody rustompm...@gmail.com wrote:

 On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote:
  On Mon, 13 Oct 2014 09:56:02 +1100
  Steven D'Aprano  wrote:
   When you have multiple clauses in the condition, it's easier to reason 
   about
   them if you write the clauses as positive statements rather than negative
   statements, that is, something is true rather than something is not
   true, and then use `not` to reverse it if you want to loop *until* the
   overall condition is true.
 
  I was just explaining this concept to a young pup the other day.  De
  Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but
  the positive logic flavor is substantially less error-prone.  People
  are fundamentally not as good at thinking about inverted logic.
 
 Curious: Which of
 
 - (not (p and q))
 - ((not p) or (not q))
 
 is more positive (less negative)??

The first is asking you to compare positive conditions (p and q) and
negate the entire thing (NAND).  The second asks you to think about
the combination of two different not true pieces of logic
(OR of two inverted inputs).  The first is pretty straightforward, and
I usually see people get it right.  The second gets screwed up as often
as not.

And of course, any combination of ands and ors should be broken into
multiple statements with a descriptive variable name in the middle or
all hope is lost.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Rustom Mody
On Monday, October 13, 2014 10:13:20 PM UTC+5:30, Rob Gaddi wrote:
 On Mon, 13 Oct 2014 09:26:57 -0700 (PDT)
 Rustom Mody  wrote:

  On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote:
   On Mon, 13 Oct 2014 09:56:02 +1100
   Steven D'Aprano  wrote:
When you have multiple clauses in the condition, it's easier to reason 
about
them if you write the clauses as positive statements rather than 
negative
statements, that is, something is true rather than something is not
true, and then use `not` to reverse it if you want to loop *until* the
overall condition is true.
   I was just explaining this concept to a young pup the other day.  De
   Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but
   the positive logic flavor is substantially less error-prone.  People
   are fundamentally not as good at thinking about inverted logic.
  Curious: Which of
  - (not (p and q))
  - ((not p) or (not q))
  is more positive (less negative)??

 The first is asking you to compare positive conditions (p and q) and
 negate the entire thing (NAND).  The second asks you to think about
 the combination of two different not true pieces of logic
 (OR of two inverted inputs).  The first is pretty straightforward, and
 I usually see people get it right.  The second gets screwed up as often
 as not.

 And of course, any combination of ands and ors should be broken into
 multiple statements with a descriptive variable name in the middle or
 all hope is lost.

Yeah I guess 2 nots is one more than one!

However (to my eyes)
while i  N  and  a[i] != X:

looks less negative than

while not (i==N or a[i] == X):

[Of course i  N is not identical to i != N ]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-13 Thread Michael Torrie
On 10/13/2014 11:12 AM, Rustom Mody wrote:
 On Monday, October 13, 2014 10:13:20 PM UTC+5:30, Rob Gaddi wrote:
 On Mon, 13 Oct 2014 09:26:57 -0700 (PDT)
 Rustom Mody  wrote:
 
 On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote:
 On Mon, 13 Oct 2014 09:56:02 +1100
 Steven D'Aprano  wrote:
 When you have multiple clauses in the condition, it's easier to reason 
 about
 them if you write the clauses as positive statements rather than negative
 statements, that is, something is true rather than something is not
 true, and then use `not` to reverse it if you want to loop *until* the
 overall condition is true.
 I was just explaining this concept to a young pup the other day.  De
 Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but
 the positive logic flavor is substantially less error-prone.  People
 are fundamentally not as good at thinking about inverted logic.
 Curious: Which of
 - (not (p and q))
 - ((not p) or (not q))
 is more positive (less negative)??
 
 The first is asking you to compare positive conditions (p and q) and
 negate the entire thing (NAND).  The second asks you to think about
 the combination of two different not true pieces of logic
 (OR of two inverted inputs).  The first is pretty straightforward, and
 I usually see people get it right.  The second gets screwed up as often
 as not.
 
 And of course, any combination of ands and ors should be broken into
 multiple statements with a descriptive variable name in the middle or
 all hope is lost.
 
 Yeah I guess 2 nots is one more than one!
 
 However (to my eyes)
 while i  N  and  a[i] != X:
 
 looks less negative than
 
 while not (i==N or a[i] == X):
 
 [Of course i  N is not identical to i != N ]

Right it should have been not (i = N or a[i] == X) to be equivalent.

In assembler it's often best to reverse the condition and then use the
opposite jump mnemonic. IE, if the test is to see if a number not zero,
use the jump if zero command instead.  Often it reduces the number of
jumps required and eliminates the need to jump over the body of the if
block.

if a != 0 then jump to bigger
jump to end
bigger:
blah
blah
end:

vs

if a == 0 then jump to end
blah
blah
end:



-- 
https://mail.python.org/mailman/listinfo/python-list


while loop - multiple condition

2014-10-12 Thread Shiva
Why is the second part of while condition not being checked?

while ans.lower() != 'yes' or ans.lower()[0] != 'y':
 ans = input('Do you like python?')


My intention is if either of the conditions are true the loop should break.
But the condition after 'or' doesn't seem to evaluate.

Thanks,
Shiva.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Chris Angelico
On Mon, Oct 13, 2014 at 4:08 AM, Shiva
shivaji...@yahoo.com.dmarc.invalid wrote:
 Why is the second part of while condition not being checked?

 while ans.lower() != 'yes' or ans.lower()[0] != 'y':
  ans = input('Do you like python?')


 My intention is if either of the conditions are true the loop should break.
 But the condition after 'or' doesn't seem to evaluate.

The loop will continue while either part is true - that's what or
means. Is that what you intended it to be doing?

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Shiva

 The loop will continue while either part is true - that's what or
 means. Is that what you intended it to be doing?
 
 ChrisA
 


Yes..however, the second part of the or condition doesn't get evaluated.
So if I enter a 'y' - I expect the second part to evaluate and the loop to
break - but that doesn't seem to happen.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Roy Smith
In article mailman.14792.1413133694.18130.python-l...@python.org,
 Shiva shivaji...@yahoo.com wrote:

 Why is the second part of while condition not being checked?
 
 while ans.lower() != 'yes' or ans.lower()[0] != 'y':
  ans = input('Do you like python?')
 
 
 My intention is if either of the conditions are true the loop should break.
 But the condition after 'or' doesn't seem to evaluate.

A general rule of programming (be it Python or any other language) is to 
break up complicated code into smaller pieces which can be understood 
and tested in isolation.  Your 'while' condition is kind of hairy.  
There's a couple of complicated expressions, a logical conjuction, and 
two different negated comparisons.  That's a lot to understand all at 
once.

I would factor that out into a little function:

---
def is_yes(answer):
  if answer.lower() == 'yes':
return True
  if answer.lower()[0] == 'y':
return True
  return False

while is_yes(ans):
  ans = input('Do you like python?')
---

Now, you can play around with your is_yes() function in an interactive 
session and see what it returns for various inputs, in isolation from 
the rest of your program:

print is_yes('y')
print is_yes('yes')
print is_yes('no')
print is_yes('you bet your sweet bippy')
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Chris Angelico
On Mon, Oct 13, 2014 at 4:21 AM, Shiva
shivaji...@yahoo.com.dmarc.invalid wrote:
 The loop will continue while either part is true - that's what or
 means. Is that what you intended it to be doing?

 ChrisA



 Yes..however, the second part of the or condition doesn't get evaluated.
 So if I enter a 'y' - I expect the second part to evaluate and the loop to
 break - but that doesn't seem to happen.

Break it down into separate parts and have a look at what's happening.

while ans.lower() != 'yes' or ans.lower()[0] != 'y':
ans = input('Do you like python?')
print(ans.lower() = {!r}; first cond = {!r}, second cond {!r},
disjunction {!r}.format(
ans.lower(), (ans.lower() != 'yes'), (ans.lower()[0] != 'y'),
(ans.lower() != 'yes' or ans.lower()[0] != 'y')
))

The while loop will continue so long as the disjunction is True. See
what it's actually doing.

This is fundamental Boolean logic, a basic skill of programming.
You're going to need to master this. Look at the different pieces, and
get your head around what the 'or' operator actually does.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Shiva
Bit confusing to use in While loop - Should have used the 'and' condition
instead of OR- then it works fine.
for OR both condition need to be false to produce a false output and break
the loop.
More of SET operations.

Thanks,
Shiva

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Chris Angelico
On Mon, Oct 13, 2014 at 4:59 AM, Shiva
shivaji...@yahoo.com.dmarc.invalid wrote:
 Bit confusing to use in While loop - Should have used the 'and' condition
 instead of OR- then it works fine.
 for OR both condition need to be false to produce a false output and break
 the loop.

Correct, what you're looking for here is indeed an 'and' (also called
a conjunction, as opposed to the disjunction of 'or'). Both operators
are important; and you need to understand what they do so you know
when to use each.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 On Mon, Oct 13, 2014 at 4:59 AM, Shiva
 shivaji...@yahoo.com.dmarc.invalid wrote:
 Bit confusing to use in While loop - Should have used the 'and' condition
 instead of OR- then it works fine.
 for OR both condition need to be false to produce a false output and break
 the loop.

 Correct, what you're looking for here is indeed an 'and' (also called
 a conjunction, as opposed to the disjunction of 'or'). Both operators
 are important; and you need to understand what they do so you know
 when to use each.

The corrected version

while ans.lower() != 'yes' and ans.lower()[0] != 'y':
 ans = input('Do you like python?')

is equivalent with

while ans.lower()[0] != 'y':
 ans = input('Do you like python?')


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Chris Angelico
On Mon, Oct 13, 2014 at 6:16 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 The corrected version

 while ans.lower() != 'yes' and ans.lower()[0] != 'y':
  ans = input('Do you like python?')

 is equivalent with

 while ans.lower()[0] != 'y':

It's true that the first part is redundant, but trimming that out
wouldn't have taught the OP about boolean logic :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Denis McMahon
On Sun, 12 Oct 2014 17:08:00 +, Shiva wrote:

 while ans.lower() != 'yes' or ans.lower()[0] != 'y':

while ans.lower() is not equal to yes
   or ans.lower()[0] is not equal to y

the loop will continue to run

Note that if ans.lower() == 'y', then the first clause ( ans.lower() != 
'yes' ) is true, so the loop will continue to run, ignoring the result of 
the second clause ( ans.lower()[0] != 'y' ), This will also be the case 
if you reverse the order of the clauses.

It seems that you need a better understanding of combinatorial logic, 
perhaps http://www.ee.surrey.ac.uk/Projects/Labview/boolalgebra/
index.html#booleantheorems will help.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Tim Chase
On 2014-10-12 22:16, Marko Rauhamaa wrote:
 is equivalent with
 
 while ans.lower()[0] != 'y':
  ans = input('Do you like python?')

And still better improved with

  while ans[:1].lower() != 'y':
ans = input('Do you like python?')

in the event that len(ans)==0 (a situation which will crash the
various current examples).

It also only expends the effort to lowercase 0-or-1 characters,
rather than lowercasing an entire string just to throw away
everything except the first character.

-tkc



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Steven D'Aprano
Tim Chase wrote:

 On 2014-10-12 22:16, Marko Rauhamaa wrote:
 is equivalent with
 
 while ans.lower()[0] != 'y':
  ans = input('Do you like python?')
 
 And still better improved with
 
   while ans[:1].lower() != 'y':
 ans = input('Do you like python?')


The intention is to loop forever until the victim breaks down and accepts
that they like Python, by entering yes or y. I'm pretty sure that
entering yellow or you've got to be kidding should not break the loop.

When you have multiple clauses in the condition, it's easier to reason about
them if you write the clauses as positive statements rather than negative
statements, that is, something is true rather than something is not
true, and then use `not` to reverse it if you want to loop *until* the
overall condition is true.

When checking for equality against multiple values, instead of:

x == a or x == b or x == c

it is usually easier to use `in`:

x in (a, b, c)


So we have:

# loop so long as the victim answers yes or y
while ans.lower() in ('yes', 'y'):
ans = input('Do you like python? Well, do you?')

# loop until the victim answers yes or y
while not (ans.lower() in ('yes', 'y')):
ans = input('Do you like python? Well, do you?')


both of which work fine if the user stays mum by entering the empty string.

You can also write:

while ans.lower() not in ('yes', 'y'):
ans = input('Do you like python? Well, do you?')


if you prefer. In my opinion, that's the most readable version of all.

One last note: if you are using Python 3.3 or better, you can support
international text better by using the casefold() method rather than
lower(). In this case, it won't make a difference, but the technically
correct method for doing case-insensitive comparisons is to casefold both
strings rather than lower- or upper-case them.


-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: while loop - multiple condition

2014-10-12 Thread Chris Angelico
On Mon, Oct 13, 2014 at 11:43 AM, Dennis Lee Bieber
wlfr...@ix.netcom.com wrote:
 ONE: Python uses short circuit evaluation: for an OR, the second 
 clause
 is only looked at if the first clause is FALSE (for an AND, the first
 clause has to be TRUE before the second is evaluated).

Short-circuiting doesn't actually matter here, incidentally. It could
be eagerly evaluated and nothing would be different.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python While loop Takes too much time.

2014-07-01 Thread Jaydeep Patil
On Monday, 30 June 2014 18:16:21 UTC+5:30, Peter Otten  wrote:
 Jaydeep Patil wrote:
 
 
 
  I have did excel automation using python.
 
  In my code I am creating python dictionaries for different three columns
 
  data at a time.There are are many rows above 4000. Lets have look in below
 
  function. Why it is taking too much time?
 
  
 
  Code:
 
  
 
  def transientTestDict(self,ws,startrow,startcol):
 
  
 
  self.hwaDict = OrderedDict()
 
  self.yawRateDict = OrderedDict()
 
  
 
  rng = ws.Cells(startrow,startcol)
 
  
 
  while not rng.Value is None:
 
  r = rng.Row
 
  c = rng.Column
 
  
 
  time = rng.Value
 
  
 
  rng1 = rng.GetOffset(0,1)
 
  hwa = rng1.Value
 
  
 
  rng2 = rng.GetOffset(0,2)
 
  yawrate = rng2.Value
 
  
 
  self.hwaDict[time] = hwa,rng.Row,rng.Column
 
  self.yawRateDict[time] = yawrate,rng.Row,rng.Column
 
  
 
  rng = ws.Cells(r+1,c)
 
  
 
  
 
  
 
  Please have look in above code  suggest me to improve speed of my code.
 
 
 
 Assuming that what slows down things is neither Python nor Excel, but the 
 
 communication between these I'd try to do as much as possible in Python. For 
 
 example (untested):
 
 
 
 def transientTestDict(self, ws, startrow, startcol):
 
 self.hwaDict = OrderedDict()
 
 self.yawRateDict = OrderedDict()
 
 
 
 time_col, hwa_col, yawrate_col = range(startcol, startcol+3)
 
 
 
 for row in xrange(startrow, sys.maxint):
 
 time = ws.Cells(row, time_col).Value
 
 if time is None:
 
 break
 
 hwa = ws.Cells(row, hwa_col).Value
 
 yawrate = ws.Cells(row, yawrate_col).Value
 
 
 
 self.hwaDict[time] = hwa, row, time_col
 
 self.yawRateDict[time] = yawrate, row, time_col
 
 
 
 While this avoids cell arithmetic in Excel it still fetches every value 
 
 separately, so I have no idea if there is a significant effect.
 
 
 
 Does Excel provide a means to get multiple cell values at once? That would 
 
 likely help.



Dear Peter,
I have tested code written by you. But still it is taking same time.



Regards
Jay
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python While loop Takes too much time.

2014-07-01 Thread Peter Otten
Jaydeep Patil wrote:

 Dear Peter,
 I have tested code written by you. But still it is taking same time.

Too bad ;(

If you run the equivalent loop written in Basic from within Excel -- is that 
faster?

If you run the loop in Python with some made-up data instead of that fetched 
from Excel -- is that faster?

What I'm trying to tell you: you need to put in some work to identify the 
culprit...

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python While loop Takes too much time.

2014-07-01 Thread Denis McMahon
On Tue, 01 Jul 2014 14:40:18 +0200, Peter Otten wrote:

 What I'm trying to tell you: you need to put in some work to identify
 the culprit...

His next question was how do I read a range from excel, please give me 
an example

I gave him an example of using google to search for solutions to his 
problem. If he can't be bothered to try and solve it himslef, I'm nopt 
going to write his code for him.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Python While loop Takes too much time.

2014-06-30 Thread Jaydeep Patil
I have did excel automation using python.
In my code I am creating python dictionaries for different three columns data 
at a time.There are are many rows above 4000. Lets have look in below function. 
Why it is taking too much time?

Code:

def transientTestDict(self,ws,startrow,startcol):

self.hwaDict = OrderedDict()
self.yawRateDict = OrderedDict()

rng = ws.Cells(startrow,startcol)

while not rng.Value is None:
r = rng.Row
c = rng.Column

time = rng.Value

rng1 = rng.GetOffset(0,1)
hwa = rng1.Value

rng2 = rng.GetOffset(0,2)
yawrate = rng2.Value

self.hwaDict[time] = hwa,rng.Row,rng.Column
self.yawRateDict[time] = yawrate,rng.Row,rng.Column

rng = ws.Cells(r+1,c)



Please have look in above code  suggest me to improve speed of my code.



Regards
Jaydeep Patil
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python While loop Takes too much time.

2014-06-30 Thread Peter Otten
Jaydeep Patil wrote:

 I have did excel automation using python.
 In my code I am creating python dictionaries for different three columns
 data at a time.There are are many rows above 4000. Lets have look in below
 function. Why it is taking too much time?
 
 Code:
 
 def transientTestDict(self,ws,startrow,startcol):
 
 self.hwaDict = OrderedDict()
 self.yawRateDict = OrderedDict()
 
 rng = ws.Cells(startrow,startcol)
 
 while not rng.Value is None:
 r = rng.Row
 c = rng.Column
 
 time = rng.Value
 
 rng1 = rng.GetOffset(0,1)
 hwa = rng1.Value
 
 rng2 = rng.GetOffset(0,2)
 yawrate = rng2.Value
 
 self.hwaDict[time] = hwa,rng.Row,rng.Column
 self.yawRateDict[time] = yawrate,rng.Row,rng.Column
 
 rng = ws.Cells(r+1,c)
 
 
 
 Please have look in above code  suggest me to improve speed of my code.

Assuming that what slows down things is neither Python nor Excel, but the 
communication between these I'd try to do as much as possible in Python. For 
example (untested):

def transientTestDict(self, ws, startrow, startcol):
self.hwaDict = OrderedDict()
self.yawRateDict = OrderedDict()

time_col, hwa_col, yawrate_col = range(startcol, startcol+3)

for row in xrange(startrow, sys.maxint):
time = ws.Cells(row, time_col).Value
if time is None:
break
hwa = ws.Cells(row, hwa_col).Value
yawrate = ws.Cells(row, yawrate_col).Value

self.hwaDict[time] = hwa, row, time_col
self.yawRateDict[time] = yawrate, row, time_col

While this avoids cell arithmetic in Excel it still fetches every value 
separately, so I have no idea if there is a significant effect.

Does Excel provide a means to get multiple cell values at once? That would 
likely help.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python While loop Takes too much time.

2014-06-30 Thread marco . nawijn
On Monday, June 30, 2014 1:32:23 PM UTC+2, Jaydeep Patil wrote:
 I have did excel automation using python.
 
 In my code I am creating python dictionaries for different three columns data 
 at a time.There are are many rows above 4000. Lets have look in below 
 function. Why it is taking too much time?
 
 
 
 Code:
 
 
 
 def transientTestDict(self,ws,startrow,startcol):
 
 
 
 self.hwaDict = OrderedDict()
 
 self.yawRateDict = OrderedDict()
 
 
 
 rng = ws.Cells(startrow,startcol)
 
 
 
 while not rng.Value is None:
 
 r = rng.Row
 
 c = rng.Column
 
 
 
 time = rng.Value
 
 
 
 rng1 = rng.GetOffset(0,1)
 
 hwa = rng1.Value
 
 
 
 rng2 = rng.GetOffset(0,2)
 
 yawrate = rng2.Value
 
 
 
 self.hwaDict[time] = hwa,rng.Row,rng.Column
 
 self.yawRateDict[time] = yawrate,rng.Row,rng.Column
 
 
 
 rng = ws.Cells(r+1,c)
 
 
 
 
 
 
 
 Please have look in above code  suggest me to improve speed of my code.
 
 
 
 
 
 
 
 Regards
 
 Jaydeep Patil

Hi Jaydeep,

I agree with Peter. I would avoid moving from cell to
cell through the EXCEL interface if you can avoid.

If possible, I would try to read ranges from EXCEL into
a python list (or maybe numpy arrays) and do the processing
in Python. In the past I even dumped an EXCEL sheet as a
CSV file and then used the numpy recfromcsv function to 
process the data.

If you are really brave, dump EXCEL alltogether :) and do
all the work in Python (have you already tried IPython 
notebook?).

Regards,

Marco

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python While loop Takes too much time.

2014-06-30 Thread Gregory Ewing

marco.naw...@colosso.nl wrote:

In the past I even dumped an EXCEL sheet as a
CSV file


That's probably the only way you'll speed things up
significantly. In my experience, accessing Excel via
COM is abysmally slow no matter how you go about it.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing in a while loop?

2014-06-27 Thread Jesse Adam

Could you post 
a) what the output looks like now (sans the logging part)
b) what output do you expect


In any event, this routine does not look right to me:

def consume_queue(queue_name):
  conn = boto.connect_sqs()
  q = conn.get_queue(queue_name)
  m = q.read()
  while m is not None:
yield m
q.delete_message(m)
logger.debug('message deleted')
m = q.read()
-- 
https://mail.python.org/mailman/listinfo/python-list


multiprocessing in a while loop?

2014-05-06 Thread Johan Llewellyn
hi, I am struggling to understand how to leverage python's multiprocessing 
module in a while loop.  the examples I have found seem to assume it is known 
ahead of time how many items need to be processed.

specifically, I am reading from an external queue.  I currently process items 
one at a time until the queue is empty.  I wrote a wrapper function to handle 
connecting to the queue, pulling the next message, and deleting it when I am 
done.  ideally, I'd like to modify this wrapper function to take an additional 
argument (processes) to specify the number of messages to process 
simultaneously.

I've attached a script that captures what I am doing now.  unfortunately, the 
external queue object is not publicly accessible and I'm not quite sure how to 
set up a local object that would support testing.  any suggestions would be 
most welcome.


thanks,
Johan
#!/usr/bin/env python

import boto
import logging

LOG_FMT = '%(asctime)s - %(levelname)s - %(module)s.%(funcName)s - %(message)s'
QUEUE = 'my-queue'

logger = logging.getLogger(__name__)


# read from an external queue; items may be added during processing
def consume_queue(queue_name):
  conn = boto.connect_sqs()
  q = conn.get_queue(queue_name)
  m = q.read()
  while m is not None:
yield m
q.delete_message(m)
logger.debug('message deleted')
m = q.read()


# high variability in message processing times (seconds - hours)
def handle_message(message)
  s = message.get_body()
  logger.info(s)


def main():
  for message in consume_queue(QUEUE):
handle_message(message)


if __name__ == '__main__':
  logging.basicConfig(level=logging.DEBUG, format=LOG_FMT)
  main()

-- 
https://mail.python.org/mailman/listinfo/python-list


Thread is somehow interfering with a while loop called after the thread is started

2014-03-16 Thread Dan McInerney
Coming back to this a long time later. I figured it out a little bit after
I posted this. I wasn't aware that q.try_run() within the nfqueue module
was a blocking call
https://www.wzdftpd.net/redmine/projects/nfqueue-bindings/wiki/Examples.
I'm not sure I was even aware of what it meant to be blocking vs
nonblocking. Either way, someone from #python looked at my code and told me
nfqueue is a blocking call and I should look into something like twisted.

Twisted is a complex module but I spent a bunch of time looking at it and
eventually had some working code implementing the absolute bare essentials
as I needed them to go asynchronous. This question eventually progressed
into https://github.com/DanMcInerney/LANs.py.

Speaking of network concurrency, my recent project has been from a web
scraper point of view and I think gevents+requests or gevents+mechanize are
the way to go for that somewhat-related topic. erequests won't import due
to a bug, grequests has no way to handle exceptions in the fetching of
responses, treq can't find and fill out form logins (maybe with a POST,
haven't explored that route), and scrapy is way too big and complex for my
latest project (https://github.com/DanMcInerney/shodan_pharmer), eventlets
I'm sure CAN work with libraries other than urllib2 but it implements and
imports its own urllib2 and it is not a favorable time:effort ratio for me
to try and implement that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Thread is somehow interfering with a while loop called after the thread is started

2013-07-28 Thread Irmen de Jong
On 28-7-2013 4:29, dan.h.mciner...@gmail.com wrote:
 I have a simple scapy + nfqueue dns spoofing script that I want to turn into 
 a thread within a larger program:
 
 http://www.bpaste.net/show/HrlfvmUBDA3rjPQdLmdp/
 
 Below is my attempt to thread the program above. Somehow, the only way the 
 while loop actually prints running is if the callback function is called 
 consistently. If the callback function isn't started, the script will never 
 print running. How can that be if the while loop is AFTER the thread was 
 started? Shouldn't the while loop and the thread operate independantly?
 
 http://bpaste.net/show/0aCxSsSW7yHcQ7EBLctI/
 

Try adding sys.stdout.flush() after your print statements, I think you're 
seeing a
stdout buffering issue.


Irmen

-- 
http://mail.python.org/mailman/listinfo/python-list


Thread is somehow interfering with a while loop called after the thread is started

2013-07-27 Thread dan . h . mcinerney
I have a simple scapy + nfqueue dns spoofing script that I want to turn into a 
thread within a larger program:

http://www.bpaste.net/show/HrlfvmUBDA3rjPQdLmdp/

Below is my attempt to thread the program above. Somehow, the only way the 
while loop actually prints running is if the callback function is called 
consistently. If the callback function isn't started, the script will never 
print running. How can that be if the while loop is AFTER the thread was 
started? Shouldn't the while loop and the thread operate independantly?

http://bpaste.net/show/0aCxSsSW7yHcQ7EBLctI/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-07 Thread Mark Lawrence

On 07/05/2013 01:17, alex23 wrote:

On May 6, 10:37 pm, Mark Lawrence breamore...@yahoo.co.uk wrote:

One of these days I'll work out why some people insist on using
superfluous parentheses in Python code.  Could it be that they enjoy
exercising their fingers by reaching for the shift key in conjunction
with the 9 or 0 key?


One of these days I'll work out why some programmers consider typing
to be effort.



I think it's very important to consider this aspect.  E.g. any one using 
dynamically typed languages has to put in more effort as they should be 
typing up their test code, whereas people using statically typed 
languages can simply head down to the pub once their code has compiled.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

--
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-07 Thread Chris Angelico
On Tue, May 7, 2013 at 4:10 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 07/05/2013 01:17, alex23 wrote:

 On May 6, 10:37 pm, Mark Lawrence breamore...@yahoo.co.uk wrote:

 One of these days I'll work out why some people insist on using
 superfluous parentheses in Python code.  Could it be that they enjoy
 exercising their fingers by reaching for the shift key in conjunction
 with the 9 or 0 key?


 One of these days I'll work out why some programmers consider typing
 to be effort.


 I think it's very important to consider this aspect.  E.g. any one using
 dynamically typed languages has to put in more effort as they should be
 typing up their test code, whereas people using statically typed languages
 can simply head down to the pub once their code has compiled.

And those who are porting other people's code to a new platform have
weeks of work just to get ./configure to run, but after that it's
smooth...

Everything is variable.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-07 Thread Chris Angelico
On Tue, May 7, 2013 at 10:44 PM, Ombongi Moraa Fe
moraa.lovetak...@gmail.com wrote:
 My first language was Pascal. It was at a time in 2005 when computers were
 finally becoming popular in Africa and our year was the first time a girls
 school from our Province did a computer coursework for National Exams. (That
 was such an achievement *sigh*)

 The teacher said ... Good Programming Practice ... Use parentheses to
 format code.. or I will deduct a point from your work when I feel like it.

 Cant seem to let go of the behavior. I use parentheses in all languages.

Pretty much all such blanket advice is flawed. I cannot at present
think of any example of a Good Programming Practice suggestion that
doesn't have its exceptions and caveats. The only ones that don't are
the ones that get codified into language/syntax rules, and even there,
most of them have their detractors. Python's indentation rule is a
prime example; most people follow the advice to always indent blocks
of code, Python makes it mandatory, and some people hate Python for
it. (And yes, there have been times when I've deliberately misindented
a block of C code, because it made more logical sense that way. I can
quote examples if you like.)

The only principle that you should follow is: Think about what you're
doing. Everything else is an elaboration on that. [1]

ChrisA
[1] Matthew 22:37-40 :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-06 Thread Neil Cerutti
On 2013-05-03, John Gordon gor...@panix.com wrote:
 In auil2vfijo...@mid.individual.net Neil Cerutti ne...@norwich.edu writes:

 Not quite yet. Players who guess correctly on the fifth try don't
 get credit.

 Are you sure?  tries is initialized to zero and isn't
 incremented for the initial guess.

while (number != guess) and (tries  5):

Is the condition that concludes the game.

After the game, you are told you lost if tries is not less than
five, regardless of if number == guess.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-06 Thread Mark Lawrence

On 06/05/2013 13:06, Neil Cerutti wrote:

On 2013-05-03, John Gordon gor...@panix.com wrote:

In auil2vfijo...@mid.individual.net Neil Cerutti ne...@norwich.edu writes:


Not quite yet. Players who guess correctly on the fifth try don't
get credit.


Are you sure?  tries is initialized to zero and isn't
incremented for the initial guess.


while (number != guess) and (tries  5):

Is the condition that concludes the game.

After the game, you are told you lost if tries is not less than
five, regardless of if number == guess.



One of these days I'll work out why some people insist on using 
superfluous parentheses in Python code.  Could it be that they enjoy 
exercising their fingers by reaching for the shift key in conjunction 
with the 9 or 0 key?


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

--
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-06 Thread Neil Cerutti
On 2013-05-06, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 06/05/2013 13:06, Neil Cerutti wrote:
 On 2013-05-03, John Gordon gor...@panix.com wrote:
 In auil2vfijo...@mid.individual.net Neil Cerutti ne...@norwich.edu 
 writes:

 Not quite yet. Players who guess correctly on the fifth try don't
 get credit.

 Are you sure?  tries is initialized to zero and isn't
 incremented for the initial guess.

 while (number != guess) and (tries  5):

 Is the condition that concludes the game.

 After the game, you are told you lost if tries is not less than
 five, regardless of if number == guess.

 One of these days I'll work out why some people insist on using
 superfluous parentheses in Python code.  Could it be that they
 enjoy exercising their fingers by reaching for the shift key in
 conjunction with the 9 or 0 key?

Superflous parenthesis are sometimes a nice aid to comprehension.

I don't know about the above case, though. I don't think it hurts
anything, but it doesn't add much.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-06 Thread Roy Smith
In article mailman.1360.1367843880.3114.python-l...@python.org,
 Mark Lawrence breamore...@yahoo.co.uk wrote:

  while (number != guess) and (tries  5):
 
 One of these days I'll work out why some people insist on using 
 superfluous parentheses in Python code.  Could it be that they enjoy 
 exercising their fingers by reaching for the shift key in conjunction 
 with the 9 or 0 key?

There's lots of reasons.  Some valid, some not.

Lets dispense with the invalid reason first.  They've come from 
C/C++/Java/whatever and are used to typing parens around the conditions 
for if/for/while statements.  To them, I say, Stop trying to write 
FORTRAN code in languages that aren't FORTRAN.

In this case, however, I have no problem with the extra parens.  Look at 
these two statements:

 while (number != guess) and (tries  5):
 while number != guess and tries  5:

They have the same meaning.  To correctly interpret the second one, you 
need to know that != and  bind tighter than and. One could say that 
you should know that, and maybe you would be right.

On the other hand, I've long since given up trying to remember operator 
precedence in various languages.  If I ever have even the slightest 
doubt, I just go ahead and put in the extra parens.  It takes another 
few ms to type, and it removes all ambiguity (for both me, and every 
future person who has to read my code).  And, every once in a while, it 
keeps me from writing a subtle and hard-to-find bug because the 
precedence rules I was sure I had remembered correctly turned out to be 
wrong for the language I happened to be typing that day.

BTW, in C, I used to write:

return (foo)

for years until somebody pointed out to me that

return foo

works.  I just assumed that if I had to write:

if (foo)
while (foo)
for (foo; bar; baz)

then

return (foo)

made sense too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-06 Thread Chris Angelico
On Mon, May 6, 2013 at 11:08 PM, Roy Smith r...@panix.com wrote:
 On the other hand, I've long since given up trying to remember operator
 precedence in various languages.  If I ever have even the slightest
 doubt, I just go ahead and put in the extra parens.

If I ever have even the slightest doubt, I just go ahead and type
language operator precedence into a web search and check it :)
Aside from utter insanity like PHP's ternary operator being wrongly
associative, that covers pretty much everything.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python program, syntax error in while loop

2013-05-06 Thread rusi
On May 6, 6:08 pm, Roy Smith r...@panix.com wrote:

 BTW, in C, I used to write:

 return (foo)

 for years until somebody pointed out to me that

 return foo

 works.  I just assumed that if I had to write:

 if (foo)
 while (foo)
 for (foo; bar; baz)

 then

 return (foo)

 made sense too.

I guess its because KR always show their examples with
return (expr);
and so we all assume its the propah way
-- 
http://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   >