Assignment and comparison in one statement

Lie Lie.1296 at gmail.com
Fri May 30 05:39:20 EDT 2008


On May 24, 5:59 am, Johannes Bauer <dfnsonfsdu... at gmx.de> wrote:
> 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?



More information about the Python-list mailing list