0

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"
9
  • You have to have an else in a conditional expression. What is it supposed to assign when the condition is false? Commented Feb 22, 2021 at 23:17
  • @Barmar do nothing Commented Feb 22, 2021 at 23:17
  • 2
    Then you can't use a conditional expression. The expression always has a value. Commented Feb 22, 2021 at 23:17
  • 1
    @bakalolo Ternary statements don't work that way. You could do if row[10] == "4751": PODQS1_R10 = "4751" in a single line for a regular if statement Commented Feb 22, 2021 at 23:18
  • 1
    You could use else PODQS1_R10 to keep the same value. Commented Feb 22, 2021 at 23:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.