A C-like if statement

K

Kay Schluehr

Roy said:
It is a deliberate and fundamental design decision in Python that
assignment is a statement, not an expression with side effects. This
means you often need an "extra" line compared to a classic C "assign
and test" idiom such as you have above. I, like you, often miss the
compactness of the C idiom, but there it is.

Hmm. A statement has side-effects but it returns no value. And yes, you
can create a name within an expression producing a value in Python,
using a list/generator comprehension. The solution to Bob's problem
would look like this:

if (I for I in (a.find("3"),) ) != -1:
print "It's here: ", I
else:
print "No 3's here"


Kay
 
P

Paul Rubin

Kay Schluehr said:
Hmm. A statement has side-effects but it returns no value. And yes, you
can create a name within an expression producing a value in Python,
using a list/generator comprehension. The solution to Bob's problem
would look like this:

if (I for I in (a.find("3"),) ) != -1:
print "It's here: ", I
else:
print "No 3's here"

I think that works for list comprehensions but not generator
comprehensions. With generator comprehensions, the index variable's
scope is limited to the comprehension. With list comprehensions
there's a wart in that the index variable is still around afterwards.
 
K

Kay Schluehr

Paul said:
I think that works for list comprehensions but not generator
comprehensions. With generator comprehensions, the index variable's
scope is limited to the comprehension.

Right. It becomes even more ugly yet:

if [I for I in ("1,2,3".find("3"),) ] != [-1]:
print "It's here: ", I
else:
print "No 3's here"
With list comprehensions
there's a wart in that the index variable is still around afterwards.

Definitely, but index variable survival is nothing that entered Python
with list-comps:

for k in range(2):
print k
1

Kay
 
C

Cameron Laird

There are *reasons* why Python discourages functions with side-effects.
Side-effects make your code hard to test and harder to debug.


Then write a function! Instead of calling the try..except block in every
branch directly, pull it out into a function:

def test(s,what):
try:
i = s.index(what)
print "It's here: ", i
except ValueError:
print "No 3's here"
.
.
.
A recent piece by Collin Park <URL:
http://www.linuxjournal.com/article/8794 >
illustrates how a user-defined exception
arises so naturally in a tiny toy example
that it occurs to a teenager first program-
ming.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,285
Messages
2,571,416
Members
48,107
Latest member
AmeliaAmad

Latest Threads

Top