Reputation: 3757
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
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
Reputation: 106430
Gonna state this as a formal answer.
If your code has:
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