• google plus

How to Do Ternary Operator Assignment in Python

The syntax for the ternary operator in Python is:

[on_true] if [expression] else [on_false]

Many programming languages, including Python, have a ternary conditional operator, which is most often used for conditional variable assignment. To illustrate, consider this code:

if game_type == 'home':
	shirt = 'white'
else:
	shirt = 'green'

That's very clear, but it takes four lines of code to assign a value to game_type.

Here is how we would rewrite that using Python's ternary operator:

shirt = 'white' if game_type == 'home' else 'green'

It's still pretty clear, but much shorter. Note that the expression could be any type of expression, including a function call, that returns a value that evaluates to True or False.

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for technical training with his business expertise and to help companies benefit from both. His previous experience was in sales, business and technical training, and management. Nat has an MBA from Harvard Business School and a BA in International Relations from Pomona College.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.