using the ternary operator in Python

problem

You’re learning Python and you came across the ternary operator. Also known as the conditional operator. This operator is helpful in cases in which we need to use a value based on some boolean logic.

SOLUTION

Using the if, else keywords in one sentence.

For example, we want to store the string “positive” if a number is positive or the string “negative” if the number is negative.

ternary_operator.py
				
					number = 1
"positive" if number >= 0 else "negative"
				
			
running

If the condition: number >= 0 is True then the line will return us “positive”, otherwise “negative”

In this case:

ternary operator in Python (conditional operator)
get the number from the user

We can store this string in a variable. Also, we can ask the user to input the number as follows:

ternary_operator.py
				
					number = int(input("Enter a number: "))
sign_type = "positive" if number >= 0 else "negative"
print(sign_type)

				
			
output
ternary operator positive number example in Python
ternary operator negative number example in Python

conclusion

In this post we saw a simple example of the ternary operator in Python. It’s a very useful feature when we need to plug a bit of logic in a single line and change the result without needing an if else statement.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪