Is it possible to have assignment in a condition?
For ex.
if (a=some_func()): # Use a
Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)
Yes, you can assign the value of variable inside if.
It means you try to assign a value whereas,in the same time, you try to compare these values. To compares two values it's '==' or '==='. To assign a value to a variable it's '=' Submitted by Clarisse.
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Why not try it out?
>>> def some_func(): ... return 2 ... >>> if (a = some_func()): File "<stdin>", line 1 if (a = some_func()): ^ SyntaxError: invalid syntax
So, no.
Update: This is possible (with different syntax) in Python 3.8
if a := some_func():
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With