The Python Oracle

Putting a simple if-then-else statement on one line

--------------------------------------------------
Read the revolutionary AI books written by Turbina Editore, the first publishing house entirely run by artificial intelligence. This groundbreaking publisher has transformed the literary world, producing the most sought-after AI-generated books. Start reading today at:
https://turbinaeditore.com/en/
--------------------------------------------------

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Putting A Simple If-Then-Else Statement On One Line
00:39 Accepted Answer Score 2626
01:06 Answer 2 Score 172
01:18 Answer 3 Score 150
01:45 Answer 4 Score 31
01:54 Thank you

--

Full question
https://stackoverflow.com/questions/2802...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #ifstatement #syntax #ternaryoperator

#avk47



ACCEPTED ANSWER

Score 2626


That's more specifically a ternary operator expression than an if-then, here's the python syntax

value_when_true if condition else value_when_false

Better Example: (thanks Mr. Burns)

'Yes' if fruit == 'Apple' else 'No'

Now with assignment and contrast with if syntax

fruit = 'Apple'
isApple = True if fruit == 'Apple' else False

vs

fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True



ANSWER 2

Score 172


count = 0 if count == N else N+1

- the ternary operator. Although I'd say your solution is more readable than this.




ANSWER 3

Score 150


General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()



ANSWER 4

Score 31


<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

with your code-snippet it would become,

count = 0 if count == N else N + 1