Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can write one line if statements in Python. You can also do conditional assignment with the ternary operator.

i.e. if True: a = 1 if True else 0



Why should I need an else statement to use an if statement?


You said you missed two things in Python:

> Oh and how I miss one line if statements and conditional assignment when I'm in Python.

derac provided an example exercising both. To separate them:

One line if statements:

  if predicate: expression
Conditional assignment:

  a = 1 if predicate else 0
The else is to permit the conditional assignment, it's a ternary operation, it is not for the if statement.


Well, sorta. In practice people don't use one line statements and it's considered unpythonic. So much so I forgot it was even possible, so you're right, I was wrong. Black converts it to a multiline statement. Also, the Ruby syntax for them is better because it makes it clear it isn't a mistake.

     launch_nuclear_weapons if at_total_war
Just reads better because it doesn't look like a mistaken if statement.

By conditional assignment, I meant more something like this:

    some_var ||= 45
And I know I can do either:

    some_var = some_var or 45
    some_var = some_var if some_var else 45
But it just looks stupid and it is such a frequent need due to the way default args work for things like dicts, that it gets annoying.



> a = 1 if True else 0




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: