Ternary Operator in Python
Let us have two variables:
pythontst1 = 5
tst2 = 10
Let's check which one is bigger and display the corresponding message:
pythonif tst1 > tst2:
print('+++')
else:
print('---')
However, this condition can be written in a shorter form using ternary operator.
Its syntax looks like this:
python'message if condition 1 is true' if condition else 'message if condition 1 is false'
Let's rewrite the condition with a ternary operator:
pythonprint('+++' if tst1 > tst2 else '---')
The ternary operator should only be used in the simplest cases, as its use makes the code difficult to understand.
Задание 1
The following code is given:
pythontst = 12
if tst > 0:
print('+++')
else:
print('---')
Rewrite it using the ternary operator.
Задание 2
The following code is given:
pythontst = 'abcde'
if 'a' in tst:
print('+++')
else:
print('---')
Rewrite it using the ternary operator.