Saturday, March 2, 2024
HomeJavaPython Ternary Operator - Java Code Geeks

Python Ternary Operator – Java Code Geeks

Hiya on this tutorial, we’ll perceive the ternary operator in python programming.

1. Introduction

The ternary operator is utilized in programming languages to return output based mostly on a binary situation. It’s much like the if-else situation block just a bit neat. In python, it’s represented by the under syntax –


value_if_true if situation else value_if_false

1.1 Establishing Python

If somebody must undergo the Python set up on Home windows, please watch this hyperlink. You’ll be able to obtain Python from this hyperlink.

2. Ternary operator in python

I’m utilizing JetBrains PyCharm as my most popular IDE. You’re free to decide on the IDE of your selection.

2.1 Ternary operator Implementation file

Add the under code to the implementation file exhibiting the totally different examples in python. We are going to use three totally different approaches –

  • Single line instance
  • Examples with –
  • Nested if-else instance

# task - python ternary operator

# instance 1 - single line instance
# syntax - value_if_true if situation else value_if_false

driving_age = 17

ans = "Eligible for driving" if driving_age >= 18 else "Not eligible for driving"

print("single line instance= ", ans)

a, b = 20, 50

# instance 2 - direct instance

# instance 2a - tuples
# syntax - (if_check_is_false, if_check_is_true)[condition]

print("ntuple consequence= ", (a, b)[a > b])

# instance 2b - dictionary

val1, val2 = 'a is smaller than b', 'b is larger than a'

# if a > b is True then the worth of the true key shall be returned.
# else if a > b is False then the worth of the false key shall be returned.
print("ndictionary consequence= ", {True: val1, False: val2}[a > b])

# instance 2c - lambda
# lambda guarantee that just one expression shall be evaluated
print("nlambda consequence= ", (lambda: val2, lambda: val1)[a > b]())

# instance 3 - nested if-else instance
if a > b:
    print("na is larger than b")
    print("nb is larger than a")

3. Code run & demo

Run this python script and if all the things goes effectively the output shall be proven within the IDE console.

Fig. 1: Ternary Example Code output
Fig. 1: Ternary Instance Code output

That’s all for this tutorial and I hope the article served you with no matter you have been searching for. Completely happy Studying and don’t forget to share!

4. Abstract

On this tutorial, we realized concerning the ternary operator in python and totally different implementations which we are able to use to play. You’ll be able to obtain the supply code of this tutorial from the Downloads part.

5. Obtain the Undertaking

This was a tutorial on easy methods to use the ternary operator in python programming.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments