in c/c++, I can "assign a value to a variable" in if-statement as follows:
int a;
if ( (a = foo()) > 0)
{
printf("%d\n", a);
}
Is there any equivalent statement for python?
Not really. In Python, an assignment is a statement, whereas in C it is an expression. The condition in the if statement must be an expression in both languages.
In Python the assignment in the if condition is forbidden so you end up with a syntax error, this design decision was done to protect against error like this:
in C you can easily do:
if (a = 1) {
...
}
while you mean:
if (a == 1) {
...
}
Until today, I believe the answer was no.
I thought that to be unfortunate, so I wrote a little Python module, which I call let
, which allows you to do this kind of thing.
Install it like this:
pip install let
I believe the following will accomplish what you're looking for:
from let import let
if let(a = foo()):
print(a)
I dropped the > 0
from your answer, making the assumption that foo
will either return 0
or a positive integer. If I'm incorrect and you really do want to check if the return value is greater than 0, then this works too:
if let(a = foo()) > 0:
print(a)
let
also couples well with while
loops, if you have a function which returns something different each time until eventually it returns something False
. IE, IBM's DB2 module requires you to repeatedly call a fetch
method to get each row from the database. You could use let
to simplify the logic of looping over everything in it like this:
while let(result = db.fetch_results()):
# do whatever with result here
No you can't do this and a good job too. This style of coding leads to complex and hard to read code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.