All Courses

#### Master's In Artificial Intelligence Program in Collaboration With IBM

4.5 (1,292 Ratings)

589 Learners

#### Why You Should Learn Data Science in 2023

Sep 30th (7:00 PM) 1117 Registered
More webinars

# WHAT IS TENARY CONDITIONS.

Sulochana Kamshetty

2 years ago

Table of Content
•  Python conditions
• Using python if-else statement
• Using ternary operator
• Using Python Tuples
•  Using Python dictionaries
• Using Lambdas
• Nested Python ternary operator
We can run this conditions with single line of statements, and specially used when we want to cross verify with  Boolean conditions etc. Or the conditions where we want to check with yes or no type of questions.
Will create python conditions like
•        Anonymous functions
•       Lambda functions
•        Lambda expressions
•        Lambda abstractions
•      Lambda form
•       Function literals
•        Boolean expressions…
•         While conditions
•           If else statements
•          for loop conditions etc
Let’s write one simple program, which compare two integers -
a. Using python if-else statement -
``````>>> x, y = 7, 8

>>> if x>y:

print("x")

else:

print("y")

``````
output : y
explaination :- which is 8 since we gave the condition, in single line if my given condition is satisfied by if else statement then print the output.
b. Using ternary operator
``````>>> x, y = 5, 6

>>> print("x" if x> y else "y")

y

>>> def find_max(a,b):

return a if (a>b) else b

>>> find_max(5, 6)``````
output:- 6
Way to implement Ternary Operator
Below are different ways to implement ternary operator.
c. Using Python Tuples
output:- 'b:0.5497848117028667'
d. Using Python dictionaries
``````>>> a, b = random(), random()

>>> {False: f"b:{b}", True: f"a:{a}"}[a>b]

'a:0.8089581560973976'

# We can interchange the key-value pair -

>>> {True: f"a:{a}", False: f"b:{b}"}[a>b]

``````
output:- 'a:0.8089581560973976'
e. Using Lambdas
We can use python lambda function to act as a ternary operator -
``>>> (lambda: f"a:{a}", lambda: f"b:{b}")[a>b]()``
output:- 'b:0.6780078581465793'
f.Nested Python ternary operator
Let’s try changing these operators
``````>>> from random import random

>>> x = random()

>>> "Less than zero" if x<0 else "between 0
and 5" if a>=0 and a<=5 else "Greather than five"``````
Output :- 'between 0 and 5'
Let’s check the actual value of x -
>>> x
0.08009251123993566
python.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.Thanks for reading…Happy Learning…