By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,428 Members | 1,340 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,428 IT Pros & Developers. It's quick & easy.

Assignment and comparison in one statement

P: n/a
Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
printf("%d\n", q);
}

or translated to Python:

if (p = myfunction()):
print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

Thanks a lot,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
in de.sci.electronics <47***********************@news.freenet.de>
Jun 27 '08 #1
Share this Question
Share on Google+
16 Replies


P: n/a
On May 23, 6:59 pm, Johannes Bauer <dfnsonfsdu...@gmx.dewrote:
Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
printf("%d\n", q);

}

or translated to Python:

if (p = myfunction()):
print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

p = myfunction()
if p:
print p

(I recommend doing it this way in C, too.)

For the case where you want to do this in an elif-clause, look for the
recent thread "C-like assignment expression?" which list some
workarounds. Or just Google this newsgroup for "assignment
expression". It's one of few minor irritating things in Python
syntax.
Carl Banks
Jun 27 '08 #2

P: n/a
On May 23, 6:59*pm, Johannes Bauer <dfnsonfsdu...@gmx.dewrote:
Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
* * * * printf("%d\n", q);

}

or translated to Python:

if (p = myfunction()):
* * * * print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?
The most obvious and readable of course: use two statements, as one
should do regardless of the language, instead of resorting to error-
prone hacks.

George
Jun 27 '08 #3

P: n/a
On 06:59, sabato 24 maggio 2008 Johannes Bauer wrote:
However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?
If you want speak a language that isn't understood mostly you'll face
unexpected risults.
When you got started with C/C++, were you writing plain english to do
programs?
Far away to be a flame, each language have its own grammar that some time it
will need to be learnt.
Therefore, even myself still bad to write english, since my mind thinking
italian sentences.

Jun 27 '08 #4

P: n/a
Carl Banks schrieb:
p = myfunction()
if p:
print p

(I recommend doing it this way in C, too.)
This is okay for if-clauses, but sucks for while-loops:

while (fgets(buf, sizeof(buf), f)) {
printf("%s\n", buf);
}

is much shorter than

char *tmp;
tmp = fgets(buf, sizeof(buf), f);
while (tmp) {
printf("%s\n", buf);
tmp = fgets(buf, sizeof(buf), f);
}
For the case where you want to do this in an elif-clause, look for the
recent thread "C-like assignment expression?" which list some
workarounds. Or just Google this newsgroup for "assignment
expression". It's one of few minor irritating things in Python
syntax.
Alright, I will. Thanks.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
in de.sci.electronics <47***********************@news.freenet.de>
Jun 27 '08 #5

P: n/a
George Sakkis schrieb:
>However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

The most obvious and readable of course: use two statements, as one
should do regardless of the language, instead of resorting to error-
prone hacks.
As I said in the reply to Carl, this might be okay for if-clauses, but
is bothering me with while-loops.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
in de.sci.electronics <47***********************@news.freenet.de>
Jun 27 '08 #6

P: n/a
TheSaint schrieb:
On 06:59, sabato 24 maggio 2008 Johannes Bauer wrote:
>However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

If you want speak a language that isn't understood mostly you'll face
unexpected risults.
When you got started with C/C++, were you writing plain english to do
programs?
Far away to be a flame, each language have its own grammar that some time it
will need to be learnt.
Therefore, even myself still bad to write english, since my mind thinking
italian sentences.
Well, I do not really see your point - of couse I'm aware (and admitted)
that my Python skills are extremely amateurish. That's why I'm asking
for help here...

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
in de.sci.electronics <47***********************@news.freenet.de>
Jun 27 '08 #7

P: n/a
On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote:
Carl Banks schrieb:
>p = myfunction()
if p:
print p

(I recommend doing it this way in C, too.)

This is okay for if-clauses, but sucks for while-loops:

while (fgets(buf, sizeof(buf), f)) {
printf("%s\n", buf);
}

is much shorter than

char *tmp;
tmp = fgets(buf, sizeof(buf), f);
while (tmp) {
printf("%s\n", buf);
tmp = fgets(buf, sizeof(buf), f);
}
Can be written in Python as:

from functools import partial

# ...

for buf in iter(partial(f.read, buf_size), ''):
print '%s\n' % buf

Ciao,
Marc 'BlackJack' Rintsch
Jun 27 '08 #8

P: n/a
On Sat, 24 May 2008 13:13:08 +0200, Johannes Bauer wrote:
George Sakkis schrieb:
>>However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

The most obvious and readable of course: use two statements, as one
should do regardless of the language, instead of resorting to error-
prone hacks.

As I said in the reply to Carl, this might be okay for if-clauses, but
is bothering me with while-loops.
Then try to write the ``while`` loop as ``for`` loop and move the
comparison into a generator function, or use the two argument variant of
`iter()`, or `itertools.takewhile()`.

Ciao,
Marc 'BlackJack' Rintsch
Jun 27 '08 #9

P: n/a
Johannes Bauer pisze:
I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
printf("%d\n", q);
}

or translated to Python:

if (p = myfunction()):
print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?
Assignment operation (or, as we prefer calling: "binding value to name")
has no boolean value, because it succeeds always. While call to
myfunction can return any value, binding it to name p has no value at all.

Tell us your objective, so we could show you "proper way" (tm). ;)

--
Jarek Zgoda
http://zgodowie.org/

"We read Knuth so you don't have to" - Tim Peters
Jun 27 '08 #10

P: n/a
On May 24, 6:12*am, Johannes Bauer <dfnsonfsdu...@gmx.dewrote:
Carl Banks schrieb:
p = myfunction()
if p:
* * print p
(I recommend doing it this way in C, too.)

This is okay for if-clauses, but sucks for while-loops:

while (fgets(buf, sizeof(buf), f)) {
* * * * printf("%s\n", buf);

}

is much shorter than

char *tmp;
tmp = fgets(buf, sizeof(buf), f);
while (tmp) {
* * * * printf("%s\n", buf);
* * * * tmp = fgets(buf, sizeof(buf), f);

}
For the case where you want to do this in an elif-clause, look for the
recent thread "C-like assignment expression?" which list some
workarounds. *Or just Google this newsgroup for "assignment
expression". *It's one of few minor irritating things in Python
syntax.

Alright, I will. Thanks.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." * * - * * Wolfgang Gerber
* * * *in de.sci.electronics <47fa8447$0$11545$9b622...@news.freenet.de>
I posted this to the other thread, but I'm afraid it might get buried
over there. See if this works for you.

class TestValue(object):
"""Class to support assignment and test in single operation"""
def __init__(self,v=None):
self.value = v

"""Add support for quasi-assignment syntax using '<<' in place of
'='."""
def __lshift__(self,other):
self.value = other
return self

def __bool__(self):
return bool(self.value)
__nonzero__ = __bool__
import re

tv = TestValue()
integer = re.compile(r"[-+]?\d+")
real = re.compile(r"[-+]?\d*\.\d+")
word = re.compile(r"\w+")

for inputValue in ("123 abc -3.1".split()):
if (tv << real.match(inputValue)):
print "Real", float(tv.value.group())
elif (tv << integer.match(inputValue)):
print "Integer", int(tv.value.group())
elif (tv << word.match(inputValue)):
print "Word", tv.value.group()

Prints:

Integer 123
Word abc
Real -3.1

In your examples, this could look like:

tv = TestValue()
while (tv << fgets(buf, sizeof(buf), f)) {
printf("%s\n", tv.value);

or:

if (tv << myfunction()):
What do you think? Is '<<' close enough to '=' for you?

-- Paul
Jun 27 '08 #11

P: n/a
On 2008-05-23, Johannes Bauer <df***********@gmx.dewrote:
I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
printf("%d\n", q);
}

or translated to Python:

if (p = myfunction()):
print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?
p = myfunction()
if p:
print p

In Python, assignment isn't an operator, it's a statement. The
condition in an if/while has to be an expression, not a
statement.

--
Grant

Jun 27 '08 #12

P: n/a
On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote:
char *tmp;
tmp = fgets(buf, sizeof(buf), f);
while (tmp) {
printf("%s\n", buf);
tmp = fgets(buf, sizeof(buf), f);
}
I think a more Pythonic way to write this, in general, would be:

while (1) {
char *tmp = fgets(buf, sizeof(buf), f);
if (!tmp)
break;
printf("%s\n", buf);
}

In actual Python, that's:

while True:
buf = f.readline()
if not buf:
break
print buf

Yeah, it's longer than the traditional C way, but you don't need to have
duplicate fgets() (or whatever) lines. On the plus side, you're less
likely to get '=' and '==' accidentally swapped in Python.

For this specific example, it can be cut down much more:

for buf in f.readlines():
print buf

(BTW, all of the above result in doublespacing the original file, but
that's what your C version was doing, so I kept it that way.)

--
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on
Jun 27 '08 #13

P: n/a
On May 24, 7:12 am, Johannes Bauer <dfnsonfsdu...@gmx.dewrote:
Carl Banks schrieb:
p = myfunction()
if p:
print p
(I recommend doing it this way in C, too.)

This is okay for if-clauses, but sucks for while-loops:

while (fgets(buf, sizeof(buf), f)) {
printf("%s\n", buf);

}

In earlier times, the Python idiom was this:

while True:
line = f.readline()
if not line:
break
print line

Not the prettiest thing ever, but it works fine, is readable, and
avoids a temporary variable. In C, given the choice between this or
using assignment expression, I'd say use either one. (But don't use
the version with a temporary, that's ugly as hell.)

More recent versions of Python have obviated the need to use this
idiom by making it possible to iterate over the lines of a file
directly. First they added xreadlines:

for line in xreadlines(f):
print line

Then they deprecated the xreadline function and made it a method:

for line in f.xreadlines():
print line

Then they recommended you no longer use that, and just made file
objects directly iterable:

for line in f:
print line

The point is, the Python language developers do share your concern
about these things. However, they still think assignment epxressions
are a very bad idea, so they've sought other solutions to these
issues.

(But, as I said, they have yet to provide an alternative for elif
clauses; you're stuck with workarounds there.)
Carl Banks
Jun 27 '08 #14

P: n/a
On 19:14, sabato 24 maggio 2008 Johannes Bauer wrote:
Well, I do not really see your point
You wrote C statements and I felt that you were trying to apply to python
interpreter.
I think that a minimun of knoweledge on python grammar it's the base for
doing some programming.
If your examples were there only to explain your meaning, then I'm wrong
here.

Jun 27 '08 #15

P: n/a
Lie
On May 24, 5:59*am, Johannes Bauer <dfnsonfsdu...@gmx.dewrote:
Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
* * * * printf("%d\n", q);

}

or translated to Python:

if (p = myfunction()):
* * * * print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

Thanks a lot,
Johannes
Python often tries to avoid things it considers "bad design" in a
language, "assignment and comparison" is, for example, a bad design
because it is easily mistaken with "equality comparison", among other
things. This avoidance of bad design sometimes go as far as making
"the way" to do something in python completely different than doing
the same thing in other languages, thus it is always a good idea to
state what you intent in doing, rather than stating what you think you
need to do. An example is python's notion for 'for' loop, which can
only loop a list, most people coming from other languages would use
range/xrange here and there, a pythonic code would only rarely use a
range/xrange (usually in situations where the number of repetition is
constant).

Try reasking by stating what you wanted to do, rather than the
abstract question that states what you think you need to do you've
just asked. What functions you wanted to use and for what?
Jun 27 '08 #16

P: n/a
On May 30, 7:39 pm, Lie <Lie.1...@gmail.comwrote:
An example is python's notion for 'for' loop, which can
only loop a list[...]
Actually, the for statement steps through any object that provides an
iterator interface. Lists just happen to be one such object type.

Jun 27 '08 #17

This discussion thread is closed

Replies have been disabled for this discussion.