[Tutor] try except continue (fwd)
Smith, Jeff
jsmith at medplus.com
Wed Aug 24 21:05:13 CEST 2005
The problem with the original solutions is that strings are immutable so
if not line.strip():
continue
doesn't actually remote the new line from the end so when you do
print line
you get two new lines: one from the original and one from the print
command. You either need
import sys
for line in sys.stdin:
if not line.strip():
continue
print line, #<-- note the comma
or my preference
import sys
for line in sys.stdin:
line = line.strip()
if not line:
continue
print line
Jeff
-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu]
Sent: Wednesday, August 24, 2005 2:29 PM
To: Tutor
Subject: Re: [Tutor] try except continue (fwd)
---------- Forwarded message ----------
Date: Wed, 24 Aug 2005 11:24:44 -0700
From: tpc247 at gmail.com
Reply-To: tpc at csua.berkeley.edu
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] try except continue
hi Danny, I finally had a chance to review your explanation of continue
you wrote a while back, and I think I understand it. You say the
program will filter empty lines from standard input. I expected the
behavior to be such that, upon running the program, and typing:
hello
Danny
and pressing ctrl-d, I would get:
hello
Danny
Instead, I got the former output, which surprised me. Why doesn't your
program work as I expected ? I then wondered what your program would do
if I slightly modified it. *grin*
import sys
for line in sys.stdin:
print line
This time, running the same former test, I got the following output:
hello
Danny
As you can see, there are three empty lines now, not just one ! Where
did the extra empty lines come from ?
On 7/28/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> Hi Tpc,
>
> I should have written an example of 'continue' usage to make things
> more explicit. Here is a simple example:
>
> ###
> """Filters empty lines out of standard input."""
> import sys
> for line in sys.stdin:
> if not line.strip():
> continue
> print line
> ######
>
> This is a small program that filters out empty lines from standard
> input. The 'continue' statement causes us to immediately jump back to
> the beginning of the loop and to keep going.
>
>
>
>
> In Python, continue is intrinstically tied with Python's looping
> operations (while/for).
>
> http://www.python.org/doc/ref/continue.html
>
> It has very little to do with exception handling, except where the
> footnotes mentions certain artificial limitations in using it within
> an exception-handling block.
>
>
_______________________________________________
Tutor maillist - Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list