How to Assign a Variable in an If Condition, and Then Return It

How to assign a variable in an IF condition, and then return it?

I see somebody else has already pointed to my old "assign and set" Cookbook recipe, which boils down in its simplest version to:

class Holder(object):
def set(self, value):
self.value = value
return value
def get(self):
return self.value

h = Holder()

...

if h.set(isBig(y)): return h.get()

However, this was intended mostly to ease transliteration between Python and languages where assignment is directly supported in if or while. If you have "hundreds" of such check-and-return in a cascade, it's much better to do something completely different:

hundreds = isBig, isSmall, isJuicy, isBlah, ...

for predicate in hundreds:
result = predicate(y)
if result: return result

or even something like

return next(x for x in (f(y) for f in hundreds) if x)

if it's OK to get a StopIteration exception if no predicate is satisfied, or

return next((x for x in (f(y) for f in hundreds) if x)), None)

if None is the proper return value when no predicate is satisfied, etc.

Almost invariably, using (or even wishing for;-) the Holder trick/non-idiom is a "design smell" which suggests looking for a different and more Pythonic approach -- the one case where Holder is justified is exactly the special case for which I designed it, i.e., the case where you want to keep close correspondence between the Python code and some non-Python (you're transliterating a reference algorithm in Python and want it working first before refactoring it into a more Pythonic form, or you're writing Python as a prototype that will be transliterated into C++, C#, Java, etc, once it's working effectively).

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;

Assign variable in if condition statement, good practice or not?

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===. For example, when you see this:

if (value = someFunction()) {
...
}

you don't know if that's what they meant to do, or if they intended to write this:

if (value == someFunction()) {
...
}

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

if ((value = someFunction()) === <whatever truthy value you are expecting>) {
...
}

Assigning value to variable using if statement

You cannot use a statement to assign into a variable. For the alternate solution use conditional/Ternary operator

Syntax

const var_name = condition ? true_value : false_value

Example

const w = 2 > 1 ? 1500 : 2500

How do I return this variable using if statements?

That is because it doesn't have a default value set explicitly. Set isPassable to False by default and you're done.


Also you can do something like this:

return (!(x < 0 || x >= 20) && (y < 0 || y >= 20))

EDIT: The above solution would only work if an AND relationship would exist between your IFs.

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.

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.

Can I assign a variable to the result of an if statement in javascript?

Try using the ? operator.

var result = (someVariable === 2 ? something : (someOtherVariable ? somethingElse : null));

The operator works like this:

boolean ? result if true : result if false;

Assign value from if condition to a variable if true with in condition itself in Java

While less readable, this is precisely what the ternary operator is for.

List<Bags> bags = (listOfBags != null && listOfBags.getBags() != null) ? listOfBags.getBags() : null;

I personally would have stuck with a simple if-statement because it's more readable:

List<Bags> bags = null;
if(listOfBags != null && listOfBags.getBags() != null) {
bags = listOfBags.getBags();
}

Both do the same thing.


You could, of course, try to make the ternary operator more readable by extracting a boolean representing the conditional ...

boolean hasBags = listOfBags != null && listOfBags.getBags() != null;
List<Bag> bags = hasBags? listOfBags.getBags() : null;

... but that that point you might as well just use an if-statement.

Put a condition check and variable assignment in one 'if' statement

First, it assigns the value of B to A (A = B), then it checks if the result of this assignment, which is A and evaluates to 1, is equal to 1.

So technically you are correct: On the way it checks A against 1.

To make things easier to read, the code is equivalent to:

UINT A, B = 1;
A = B;
if(A == 1){
return(TRUE);
} else {
return(FALSE);
}


Related Topics



Leave a reply



Submit