Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line if-condition-assignment

People also ask

How do you write if condition in one line?

One-Line If Statement (Without Else)A single-line if statement just means you're deleting the new line and indentation. You're still writing the same code, with the only twist being that it takes one line instead of two.

Can we use assignment operator in if condition in Python?

No. Assignment in Python is a statement, not an expression.

Can we assign value in if condition?

Yes, you can assign the value of variable inside if.

Can we write if-else in one line in Python?

Python If Statement In One Line In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.


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.


Use this:

num1 = 20 if someBoolValue else num1

In one line:

if someBoolValue: num1 = 20

But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.

if someBoolValue:
    num1 = 20

(Equally, camel caps should be avoided. So rather use some_bool_value.)

Note that an in-line expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.


you can use one of the following:

(falseVal, trueVal)[TEST]

TEST and trueVal or falseVal

No. I guess you were hoping that something like num1 = 20 if someBoolValue would work, but it doesn't. I think the best way is with the if statement as you have written it:

if someBoolValue:
    num1 = 20