473,406 Members | 2,620 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

A C-like if statement

I miss being able to do something like this in Python

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

where I gets assigned the index returned by find() AND the if statement gets
to do its job in the same line. Then you don't have to have another like
that specifically gets the index of the "3". Is there a way to do this in
Python?

Thanks!

Bob
Feb 23 '06 #1
23 1458
Bob Greschke <bo*@passcal.nmt.edu> wrote:
I miss being able to do something like this in Python

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

where I gets assigned the index returned by find() AND the if statement gets
to do its job in the same line. Then you don't have to have another like
that specifically gets the index of the "3". Is there a way to do this in
Python?


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.

It's also unpythonic to return magic values to indicate failure.
Throwing an exception would be the more normal way of doing it. So,
I'd expect the above to translate into something like:

try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"
Feb 23 '06 #2

"Roy Smith" <ro*@panix.com> wrote in message
news:dt**********@reader2.panix.com...
Bob Greschke <bo*@passcal.nmt.edu> wrote:
I miss being able to do something like this in Python

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

where I gets assigned the index returned by find() AND the if statement
gets
to do its job in the same line. Then you don't have to have another like
that specifically gets the index of the "3". Is there a way to do this in
Python?


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.

It's also unpythonic to return magic values to indicate failure.
Throwing an exception would be the more normal way of doing it. So,
I'd expect the above to translate into something like:

try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"


Nuts. I guess you're right. It wouldn't be proper. Things are added or
proposed every day for Python that I can't even pronounce, but a simple 'if
(I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
to BASIC. :)

I think your way would work if .find() were replaced with .index(). I'm
just trying to clean up an if/elif tree a bit, so using try would make
things bigger.

Thanks!

Bob
Feb 23 '06 #3
But maybe we're talking about string methods so to get an exception
we'd want to use "index" instead of "find".

Giles

Feb 23 '06 #4
On Thu, 23 Feb 2006 12:04:38 -0700 in comp.lang.python, "Bob Greschke"
<bo*@passcal.nmt.edu> wrote:

"Roy Smith" <ro*@panix.com> wrote in message
news:dt**********@reader2.panix.com...

[...]
try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"


Nuts. I guess you're right. It wouldn't be proper. Things are added or
proposed every day for Python that I can't even pronounce, but a simple 'if
(I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
to BASIC. :)


I think you'll find that BASIC doesn't allow it either...

Of the "missing" "features" of Python, this one is waaaaaay down on my
list. In fact, it's not there at all. What I _really_ miss is
do{...}while. The best workaround I've found is unaesthetic, IMHO:

while 1:
# stuff
if exit_condition: break

Regards,
-=Dave

--
Change is inevitable, progress is not.
Feb 23 '06 #5
On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:
try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"
Nuts. I guess you're right. It wouldn't be proper. Things are added or
proposed every day for Python that I can't even pronounce, but a simple 'if
(I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
to BASIC. :)


There are *reasons* why Python discourages functions with side-effects.
Side-effects make your code hard to test and harder to debug.
I think your way would work if .find() were replaced with .index(). I'm
just trying to clean up an if/elif tree a bit, so using try would make
things bigger.


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"
--
Steven.

Feb 23 '06 #6

Steven D'Aprano wrote:
On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:
try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"


Nuts. I guess you're right. It wouldn't be proper. Things are added or
proposed every day for Python that I can't even pronounce, but a simple 'if
(I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
to BASIC. :)


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

"test".index("a") Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
"test".index("a")
ValueError: substring not found "test".find("a")

-1

Feb 24 '06 #7
"Bob Greschke" <bo*@passcal.nmt.edu> writes:
I miss being able to do something like this in Python

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

where I gets assigned the index returned by find() AND the if statement gets
to do its job in the same line. Then you don't have to have another like
that specifically gets the index of the "3". Is there a way to do this in
Python?


For regexps I sometimes do it with a specially created class instance.
Something like:

save = Cache_match()

if save.find(a, "3"):
print "it's here:", save.result
else:
print "no 3's here"

Implementing Cache_match is left to you as an exercise. It does make
your code a bit cleaner if you're doing lots of matching.
Feb 24 '06 #8
On Fri, 24 Feb 2006 09:14:53 +1100
"Steven D'Aprano" <st***@REMOVETHIScyber.com.au> wrote:
There are *reasons* why Python discourages functions with
side-effects. Side-effects make your code hard to test and
harder to debug.


You of course meant "expressions with side-effects". Python
is pretty good at making functions with side-effects. At
least it is if you want them. ;-)

--
Terry Hancock (ha*****@AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com

Feb 24 '06 #9
On Thu, 23 Feb 2006 20:41:52 -0600, Terry Hancock wrote:
On Fri, 24 Feb 2006 09:14:53 +1100
"Steven D'Aprano" <st***@REMOVETHIScyber.com.au> wrote:
There are *reasons* why Python discourages functions with
side-effects. Side-effects make your code hard to test and
harder to debug.


You of course meant "expressions with side-effects". Python
is pretty good at making functions with side-effects. At
least it is if you want them. ;-)


Yes, of course I meant that.

However, functions with side-effects are also discouraged. Unless
side-effects are the correct way to do whatever it is you are trying to
do, in which case they are encouraged.

*wink*
--
Steven.

Feb 24 '06 #10
On Thu, 23 Feb 2006 16:49:09 -0800, bonono wrote:

Steven D'Aprano wrote:
On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:
>> try:
>> i = a.find("3")
>> print "It's here: ", i
>> except NotFound:
>> print "No 3's here"
>
> Nuts. I guess you're right. It wouldn't be proper. Things are added or
> proposed every day for Python that I can't even pronounce, but a simple 'if
> (I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
> to BASIC. :)


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

"test".index("a") Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
"test".index("a")
ValueError: substring not found "test".find("a")

-1

Did you have a point?

In case you haven't been following the entire thread, the original bit of
code above (the try block using the find method) wasn't mine. It just
happened to be quoted in my post.
Now that's a Python wart: using >>> for the prompt for interactive
sessions. It makes it ambiguous when posting code in email or newsgroups,
especially once the code gets quoted a few times.
--
Steven.

Feb 24 '06 #11

Steven D'Aprano wrote:
On Thu, 23 Feb 2006 16:49:09 -0800, bonono wrote:

Steven D'Aprano wrote:
On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:

>> try:
>> i = a.find("3")
>> print "It's here: ", i
>> except NotFound:
>> print "No 3's here"
>
> Nuts. I guess you're right. It wouldn't be proper. Things are added or
> proposed every day for Python that I can't even pronounce, but a simple 'if
> (I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
> to BASIC. :)

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

> "test".index("a")

Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
"test".index("a")
ValueError: substring not found
> "test".find("a")

-1

Did you have a point?

It was about your side-effect talk, if you failed to see it, that is
fine.

BTW, it seems that the term side-effect of function used is a bit
different from my understanding of how it is in general used in this
field.

Feb 24 '06 #12
On Fri, 24 Feb 2006 02:02:02 -0800, bonono wrote:
>>>> "test".index("a")
> Traceback (most recent call last):
> File "<pyshell#0>", line 1, in -toplevel-
> "test".index("a")
> ValueError: substring not found
>>>> "test".find("a")
> -1

Did you have a point?

It was about your side-effect talk, if you failed to see it, that is
fine.

BTW, it seems that the term side-effect of function used is a bit
different from my understanding of how it is in general used in this
field.


What side effect?

Returning magic values (e.g. -1 to indicate "not found") is not a
side-effect in any terminology I've come across.

A side-effect would be if s.index(substr) not only returned the index as
promised, but also (say) appended substr to a list somewhere.

Side-effects aren't always bad (import, for example, does all its work by
side-effect). But they are generally frowned upon, and in functional
languages they are verboten.
--
Steven.

Feb 24 '06 #13
Steven D'Aprano wrote:
Now that's a Python wart: using >>> for the prompt for interactive
sessions. It makes it ambiguous when posting code in email or newsgroups,
especially once the code gets quoted a few times.


So change it. My pythonstartup.py contains:

import sys
sys.ps1 = ' >>> '
sys.ps2 = ' ... '

Kent
Feb 24 '06 #14
Op 2006-02-23, Roy Smith schreef <ro*@panix.com>:
Bob Greschke <bo*@passcal.nmt.edu> wrote:
I miss being able to do something like this in Python

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

where I gets assigned the index returned by find() AND the if statement gets
to do its job in the same line. Then you don't have to have another like
that specifically gets the index of the "3". Is there a way to do this in
Python?


It is a deliberate and fundamental design decision in Python that
assignment is a statement, not an expression with side effects.


The only motivation I have heard for this decision is to easily
find typo related bugs. I can hardly find that a fundamental
design decision.

--
Antoon Pardon
Feb 24 '06 #15
On Fri, 24 Feb 2006 06:45:41 -0500, Kent Johnson wrote:
Steven D'Aprano wrote:
Now that's a Python wart: using >>> for the prompt for interactive
sessions. It makes it ambiguous when posting code in email or newsgroups,
especially once the code gets quoted a few times.


So change it. My pythonstartup.py contains:

import sys
sys.ps1 = ' >>> '
sys.ps2 = ' ... '


Sure, I can change my prompt. And you can change yours. And Bob can change
his. And Freddy doesn't bother. And now we've all got different prompts,
and nobody knows what's what...

It is good to be able to set your own prompt when needed. But it is also
good to have a common default prompt. And it would be good for that common
default prompt to NOT clash with email quoting standards. Therefore that
the prompt actually does clash is a wart.

That's my opinion. Yours may differ.

--
Steven.

Feb 24 '06 #16
In article <pa****************************@REMOVETHIScyber.co m.au>,
Steven D'Aprano <st***@REMOVETHIScyber.com.au> wrote:
Side-effects aren't always bad (import, for example, does all its work by
side-effect). But they are generally frowned upon, and in functional
languages they are verboten.


How do you do any I/O in a functional language if side effects are
verboten? For that matter, how does a functional program ever stop running?
Feb 24 '06 #17
Roy Smith:
How do you do any I/O in a functional language if side effects are
verboten?
The user is a function. Output is its parameter, input its return value.
The user is not allowed to maintain state ;-)
For that matter, how does a functional program ever stop running?


By returning to the caller.

--
René Pijlman
Feb 24 '06 #18
On Fri, 24 Feb 2006 08:03:49 -0500, Roy Smith wrote:
In article <pa****************************@REMOVETHIScyber.co m.au>,
Steven D'Aprano <st***@REMOVETHIScyber.com.au> wrote:
Side-effects aren't always bad (import, for example, does all its work by
side-effect). But they are generally frowned upon, and in functional
languages they are verboten.


How do you do any I/O in a functional language if side effects are
verboten? For that matter, how does a functional program ever stop running?


Fair enough.

But still, ignoring unavoidable cases like writing to a file, the ideal of
functional languages is for side-effects to not exist.

--
Steven.

Feb 24 '06 #19
Roy Smith wrote:
In article <pa****************************@REMOVETHIScyber.co m.au>,
Steven D'Aprano <st***@REMOVETHIScyber.com.au> wrote:
Side-effects aren't always bad (import, for example, does all its work by
side-effect). But they are generally frowned upon, and in functional
languages they are verboten.


How do you do any I/O in a functional language if side effects are
verboten? For that matter, how does a functional program ever stop
running?


Using Monads. Which basically starts carrying around explicit state in an
implicit manner. But that is restricted to very few, specific portions of
the program.

Diez
Feb 24 '06 #20

Roy Smith wrote:
Bob Greschke <bo*@passcal.nmt.edu> wrote:
I miss being able to do something like this in Python

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

where I gets assigned the index returned by find() AND the if statement gets
to do its job in the same line. Then you don't have to have another like
that specifically gets the index of the "3". Is there a way to do this in
Python?


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

Feb 24 '06 #21
"Kay Schluehr" <ka**********@gmx.net> writes:
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.
Feb 24 '06 #22

Paul Rubin wrote:
"Kay Schluehr" <ka**********@gmx.net> writes:
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.


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
k

1

Kay

Feb 25 '06 #23
In article <pa***************************@REMOVETHIScyber.com .au>,
Steven D'Aprano <st***@REMOVETHIScyber.com.au> wrote:
On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:
try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"


Nuts. I guess you're right. It wouldn't be proper. Things are added or
proposed every day for Python that I can't even pronounce, but a simple 'if
(I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
to BASIC. :)


There are *reasons* why Python discourages functions with side-effects.
Side-effects make your code hard to test and harder to debug.
I think your way would work if .find() were replaced with .index(). I'm
just trying to clean up an if/elif tree a bit, so using try would make
things bigger.


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"

Feb 26 '06 #24

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
by: Fábio Mendes | last post by:
I'm sorry if it's an replicate. Either my e-mail program is messing with things or the python-list sent my msg to /dev/null. I couldn't find anything related in previous PEP's, so here it goes a...
15
by: Nerox | last post by:
Hi, If i write: #include <stdio.h> int foo(int); int main(void){ int a = 3; foo(a); }
13
by: eman1000 | last post by:
I was recently looking at the prototype library (http://prototype.conio.net/) and I noticed the author used the following syntax: Object.extend(MyObj.prototype, { my_meth1: function(){},...
37
by: Steven Bethard | last post by:
The PEP below should be mostly self explanatory. I'll try to keep the most updated versions available at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt...
18
by: Steven Bethard | last post by:
I've updated the PEP based on a number of comments on comp.lang.python. The most updated versions are still at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt...
28
by: Steven Bethard | last post by:
Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions!...
7
by: Steven Bethard | last post by:
I've updated PEP 359 with a bunch of the recent suggestions. The patch is available at: http://bugs.python.org/1472459 and I've pasted the full text below. I've tried to be more explicit about...
19
by: Steve | last post by:
ASP error number 13 - Type mismatch with SELECT...FOR UPDATE statement I got ASP error number 13 when I use the SELECT...FOR UPDATE statement as below. However, if I use SELECT statement without...
18
by: dspfun | last post by:
Hi! The words "expression" and "statement" are often used in C99 and C- textbooks, however, I am not sure of the clear defintion of these words with respect to C. Can somebody provide a sharp...
23
by: florian.loitsch | last post by:
According to the spec Section 14 the production SourceElements:SourceElements SourceElement is evaluated as follows: 1. Evaluate SourceElements. 2. If Result(1) is an abrupt completion, return...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.