⊗pyPmCdTO 143 of 208 menu

Ternary Operator in Python

Let us have two variables:

tst1 = 5 tst2 = 10

Let's check which one is bigger and display the corresponding message:

if tst1 > tst2: print('+++') else: print('---')

However, this condition can be written in a shorter form using ternary operator.

Its syntax looks like this:

'message if condition 1 is true' if condition else 'message if condition 1 is false'

Let's rewrite the condition with a ternary operator:

print('+++' if tst1 > tst2 else '---')

The ternary operator should only be used in the simplest cases, as its use makes the code difficult to understand.

The following code is given:

tst = 12 if tst > 0: print('+++') else: print('---')

Rewrite it using the ternary operator.

The following code is given:

tst = 'abcde' if 'a' in tst: print('+++') else: print('---')

Rewrite it using the ternary operator.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline