Why would you use an assignment in a condition?
It's more useful for loops than if statements.
while(var = GetNext())
{
...do something with 'var'
}
Which would otherwise have to be written
var = GetNext();
while(var)
{
...do something
var = GetNext();
}
Can we have assignment in a condition?
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():
Variable assignment in an if condition
if (Derived* derived = dynamic_cast<Derived*>(base)) {
// do stuff with `derived`
}
Though this is oft cited as an anti-pattern ("use virtual dispatch!"), sometimes the Derived
type has functionality that the Base
simply does not (and, consequently, distinct functions), and this is a good way to switch on that semantic difference.
C assignments in an 'if' statement
Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false.
it would be the same as
if ((s = data[q]) != 0) return s;
How the assignment statement in an if statement serves as a condition?
Quoting C11
, chapter §6.5.16, Assignment operators (emphasis mine)
An assignment operator stores a value in the object designated by the left operand. An
assignment expression has the value of the left operand after the assignment,111) but is not
an lvalue.
So, first the assignment will happen, and then, the value that has been assigned will be used as the conditional statement in if
.
So, in case of
if (p = 0 )
will evaluate to FALSE and
if (p = 5)
will be TRUE.
Variable assignment inside an 'if' condition in JavaScript
It has nothing to do with the if
statement, but:
if(a=2 && (b=8))
Here the last one, (b=8)
, actually returns 8 as assigning always returns the assigned value, so it's the same as writing
a = 2 && 8;
And 2 && 8
returns 8
, as 2 is truthy, so it's the same as writing a = 8
.
One line if-condition-assignment
I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:
num1 = 20 if someBoolValue else num1
If you exclude else num1
, you'll receive a syntax error since I'm quite sure that the assignment must actually return something.
As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:
if someBoolValue: num1=20
I'm not a big fan of the num1 = someBoolValue and 20 or num1
for the exact same reason. I have to actually think twice on what that line is doing.
The best way to actually achieve what you want to do is the original version:
if someBoolValue:
num1 = 20
The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.
Also, as a side note, num1 = 20 if someBoolValue
is valid Ruby code, because Ruby works a bit differently.
assignment expressions with conditional expression
What about
z = int(y) if (y := expensive_function(x)).is_integer() else y
?
Actually, in a if cond else b
, there are two conditional expressions: the a
- and the b
-members. But the middle member, i.e. the cond
one is not conditional: it is always evaluated, explaining why using an assigment operator there raises no error.
A prior-to-3.8 approach (i.e. with no Walrus Operator) can be
z = (
lambda y: int(y) if y.is_integer() else y
)(
expensive_function(x)
)
Assign variable value inside if-statement
Variables can be assigned but not declared inside the conditional statement:
int v;
if((v = someMethod()) != 0) return true;
Related Topics
Sorting a List of Dot-Separated Numbers, Like Software Versions
Find Column Name in Pandas That Matches an Array
How to Find Numeric Columns in Pandas
Pandas "Can Only Compare Identically-Labeled Dataframe Objects" Error
Is It Ever Useful to Use Python's Input Over Raw_Input
Convert to Binary and Keep Leading Zeros
Counting Repeated Characters in a String in Python
Dangers of Sys.Setdefaultencoding('Utf-8')
How to Make a Surface with a Transparent Background in Pygame
Defining a Discrete Colormap for Imshow in Matplotlib
Collision Between Masks in Pygame
Multiple Variables in a 'With' Statement
How to Generate a Random Number with a Specific Amount of Digits
How to Escape Special Characters of a String with Single Backslashes
A Good Way to Get the Charset/Encoding of an Http Response in Python
Databaseerror: Current Transaction Is Aborted, Commands Ignored Until End of Transaction Block