Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.1k points)

I have a code:

ab = 'off'

if b.page == 'blog':
    ab = 'on'


print ab


Is there any other way to make it shorter in Python?

1 Answer

0 votes
by (119k points)

You can use the ternary operator to write multiple if-else statements in a single line. Here is the syntax to use the ternary operator:

[output on_true]  if  [expression]  else  [output on_false] 

Here is the shortest python code to write an if statement:

ab= 'on' if c.page=='blog' else 'off'

To become an expert in Python, I recommend this Python Course by Intellipaat that provides instructor-led training, hands-on projects, and certification. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 26, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...