< Prev
Next >

Python - Conditional Operator

Similar to C, C++ and Java programming languages, Python also gives us a feature of the conditional operator, which is also called ternary operator because it has three operands, such as -

Syntax of the conditional operator -

first-expression  if boolean-condition  else second expression

Conditional operator example.

# Python conditional operator example

a=10	#integer variable1
b=20	#integer variable2

#Conditoonal expression1
large = a if a>b else b

#Conditional expression2
str1 = 'a is less than b' if a<b  else 'a is greater than b'

#Conditional expression3
print(10   if a>b  else 100.50)

#Conditional expression4
print('y'  if a>b  else 'n')
a is less than b

Any expression of a conditional operator could even be a call to a method but this method must return a value.
#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

In the latter program, the condition of if statement in the conditional operator calls the function hasAFlower(), which returns 1 i.e. true boolean value, hence the first expression of the conditional operator, which is a call to a function getColor() is executed, which returns a string i.e. The color of flower is blue.

Note: If you don't use self keyword in function definitions then the following error is thrown by the compiler TypeError: getColor() takes 0 positional arguments but 1 was given.

In a way, the self keyword of Python is similar to this keyword of Java language, and self keyword must be included when defining a method of a class, to represent the current instance of the class.

Please share this article -

< Prev
Next >
< Python logical operators
Python Classes >


Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition