Python ternary operator

The Python ternary operator also known as the short version of if/else clause.It is indeed literally a shorter version of if and else.With ternary operator you can write a code in single line which you may require writing it in four or more lines with if and else.

Python if,else , and elif statement

The format of writing ternary operator is given below:
 
code1 if expression else code2
 
The code1 is the code to be executed if the expression is True or returns true and the ‘code2’ is the code to be executed if expression is False.Note her there is no colon(:) after the expression.

>>> new_line=1
>>> print('New line') if new_line else print('Not new line')
New line

print(‘New line’) is executed if new_line is true,which in this case is true so it is executed.If the new_line if false print(‘Not new line’) would have executed.

Another example is given below.

>>> num=100
>>> print( num ,'is smaller than 500') if num<500 else print(num , 'is greater than 500')
100 is smaller than 500
>>> #Normal if else
>>> if num<500:
	print(num ,'is smaller than 500')
else:
	print(num , 'is greater than 500')

	
100 is smaller than 500

Look how the code can be written concisely with ternary operator.But the normal if and else on the other hand requires certain indentation and colon to make the code works.



Leave a Reply

Your email address will not be published. Required fields are marked *