Advertisement
first-expression if boolean-condition else second-expression
# Python conditional operator example
a=10 #integer variable1
b=20 #integer variable2
#Conditional expression1
large = a if a>b else b
print(large)
#Conditional expression2
str1 = 'a is less than b' if a<b else 'a is greater than b'
print(str1)
#Conditional expression3
print(10 if a>b else 100.50)
#Conditional expression4
print('y' if a>b else 'n')
Output
20
a is less than b
100.5
n
#Python conditional operator example
#Defining a class and its integer attribute
class A :
x=5
#Initializing a variable with an object of A class
ob = A()
#Initializing a variable with a boolean 1(true) value
bool_value = 1
#Conditional expression1
print('yes' if 5>10 else 'no')
#Conditional expression2
print(ob if bool_value else 'Object of class A does not exist');
#Conditional expression3
print(ob.x if bool_value else 'Object of class A does not exist');
no
<__main__.A object at 0x0000000002ED67B8>
5
Advertisement
#Conditional expression returning a string value
#Conditional expression1
print('5 is greater than 10' if 5>10 else '10 is greater than 5')
#Conditional expression2
print('a is greater than b' if 'a'>'b' else 'b is greater than a')
10 is greater than 5
b is greater than a
#Python conditional operator example
a=10 #integer variable1
b=20 #integer variable2
#First expression of this conditional operator is missing
print( if a>b else 20)
#Python conditional operator example
a,b = 10,5 #Assigning 10 to a and 5 to b
#Conditional operator expression
print(10 if a>b else 5)
#Second conditional operator expression
print("a is less than b" if a<b else None);
10
None
#Defining a class Flower with two functions
class Flower :
#First function
def hasAFlower(self):
return 1
#Second function
def getColor(self):
return "The color of this flower is blue"
#Creating an object of class Flower
ob = Flower()
#Conditional expression
print(ob.getColor() if ob.hasAFlower() else 'Does not have a flower')
The color of this flower is blue
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement