Assignment and comparison in one statement

Grant Edwards grante at visi.com
Sat May 24 12:36:36 EDT 2008


On 2008-05-23, Johannes Bauer <dfnsonfsduifb at gmx.de> wrote:

> 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




More information about the Python-list mailing list