I have this
bc = 'off' if c.page == 'blog': bc = 'on' print(bc)
Is there a more pythonic (and/or shorter) way of writing this in Python?
Python if Statement Syntax In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as True . None and 0 are interpreted as False .
Use If/Else Statements in One Line To simplify the code and reduce the number of lines in the conditional statements, you can use an inline if conditional statement. Consider the following concise code that performs the same with one line for each if/else conditional statement.
Shortest one should be:
bc = 'on' if c.page=='blog' else 'off'
Generally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With