Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter, more pythonic way of writing an if statement

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?

like image 738
32423hjh32423 Avatar asked Aug 23 '09 18:08

32423hjh32423


People also ask

What is the correct way of writing an if statement 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 .

How do I reduce the amount of an if statement in Python?

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.


1 Answers

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.

like image 190
freiksenet Avatar answered Sep 20 '22 15:09

freiksenet