Lightsout
Lightsout

Reputation: 3757

python how to write one line if statement

I am trying to write a one line if statement with no else. What is the correct way to do this? I want the statement to do nothing if the if condition is not matched.

PODQS1_R10 = ""
PODQS2_R11 = ""
PODQS3_R12 = ""
    
PODQS1_R10 = "4751" if row[10] == "4751"

Upvotes: 0

Views: 5491

Answers (2)

maciejwww
maciejwww

Reputation: 1196

You have to use else, there is no other way when using one line if.. else statement. But, it looks really similar and I think it shouldn't be a problem.

One line if.. else statement schema:

variable = value_if_condition_true if condition else value_if_condition_false

In your case:

PODQS1_R10 = "4751" if row[10] == "4751" else None

[without else] The only way to keep away from using else is classic if.. else statement without any action in the opposite case:

if row[10] == "4751":
    PODQS1_R10 = "4751"

The compilator will just skip creating PODQS1_R10.

[TIP] Try to avoid using one line if.. else statements because code loses its clarity.

[TIP 2] Following PEP8, dont't use UPPER CASE as a variable name.

Upvotes: 1

Makoto
Makoto

Reputation: 106430

Gonna state this as a formal answer.

If your code has:

  • Obscure-looking variable names with no real rhyme or reason to a new maintainer, and
  • tough-to-spot at a first glance requirements as to why a value should be something,

then the last thing you should do is put the if statement on one line.

You don't have to have an else statement with an if statement anyway.

if row[10] == "4751":
    PODQS1_R10 = "4751"

There may even be an opportunity to streamline that a little by assigning it the contents of the list if you know that they're equal anyway.

if row[10] == "4751":
    PODQS1_R10 = row[10]

Upvotes: 0

Related Questions