Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do conditional assignment in python

Tags:

python

I tend to use this a lot, but it's ugly:

a = (lambda x: x if x else y)(get_something())

So I wrote this function:

def either(val, alt):
    if val:
        return val
    else:
        return alt

So you can do:

a = either(get_something(), y)

Is there a built-in function for this (similar to ISNULL in T-SQL)?

like image 501
crizCraig Avatar asked Jul 15 '11 08:07

crizCraig


People also ask

Can we use assignment operator in if condition in Python?

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

How do you write a conditional statement in Python?

The statement can be a single line or a block of code. #If the condition is true, the statement will be executed. num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.

What does := in Python mean?

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

What are the two main types of conditional statements in Python?

We use those statements while we want to execute a block of code when the given condition is true or false. Type of condition statement in Python: If statement. If Else statement.


3 Answers

The or operator does what you want:

get_something() or y

In fact, it's chainable, like COALESCE (and unlike ISNULL). The following expression evaluates to the left-most argument that converts to True.

A or B or C
like image 122
Marcelo Cantos Avatar answered Nov 04 '22 07:11

Marcelo Cantos


You may use:

a = get_something() or y

If get_something is True in boolean context, its value will be assigned to a. Otherwise - y will be assigned to a.

like image 30
Michał Bentkowski Avatar answered Nov 04 '22 08:11

Michał Bentkowski


Easy!

For more conditional code:

a = b if b else val

For your code:

a = get_something() if get_something() else val

With that you can do complex conditions like this:

a = get_something() if get_something()/2!=0 else val
like image 42
Phyo Arkar Lwin Avatar answered Nov 04 '22 06:11

Phyo Arkar Lwin