473,288 Members | 1,771 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,288 software developers and data experts.

Assignment and comparison in one statement

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
16 7290
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Paul Rubin | last post by:
OK, I want to scan a file for lines matching a certain regexp. I'd like to use an assignment expression, like for line in file: if (g := re.match(pat, line)): croggle(g.group(1)) Since...
17
by: shank | last post by:
I'm coming from the ASP worl and have no clue to javascript. In the following code, I'm trying to set the value for variable strPage, then use that in the redirect statement. The page does nothing....
15
by: grunar | last post by:
After some thought on what I need in a Python ORM (multiple primary keys, complex joins, case statements etc.), and after having built these libraries for other un-named languages, I decided to...
16
by: Tim923 | last post by:
From my days of programming Pascal in the early 1990s, I remember using ":=" for assignment and "=" for equality, but someone else remembers "=" and "==" just like C#. Does anyone remember? -...
14
by: Santi | last post by:
I see in some code, I don´t remember now if it is c# or c++, that the when they perform a comparison they use the value first and then the variable, like: if( null == variable ){} Is there an...
34
by: Chris | last post by:
Is there ever a reason to declare this as if(*this == rhs) as opposed to what I normally see if(this == &rhs) ?
20
by: TimeHorse | last post by:
I would like to gauge interest in the following proposal: Problem: Assignment statements cannot be used as expressions. Performing a list of mutually exclusive checks that require data...
8
by: Johs | last post by:
In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this code example: #include <iostream.h> int result; // the result of the calculations char oper_char; // the user-specified...
5
MMcCarthy
by: MMcCarthy | last post by:
Hi guys, I know I must be missing something obvious here. Can anyone spot why the if statement is not reading true. Function checkCummLeave(dateCheck As Date, dayAmt As Integer) Dim db As...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.