../_images/book_cover.jpg

This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

< 4.1 If-Else Statements | Contents | 4.3 Summary and Problems >

Ternary Operators

Most programming languages have ternary operators, which usually known as conditional expressions. It provides a way that we can use one-line code to evaluate the first expression if the condition is true, otherwise it evaluates the second expression. Python has its way to implement the ternary operator, which can be constructed as below:

CONSTRUCTION: ternary operator in Python

expression_if_true if condition else expression_if_false

EXAMPLE: Ternary operator

is_student = True
person = 'student' if is_student else 'not student'
print(person)
student

From the above example, we can see this one-line code is equivalent to the following block of codes.

is_student = True
if is_student:
    person = 'student'
else:
    person = 'not student'
print(person)
student

Ternary operator provides a simple way for branching, and it can make our codes concise. Besides, in the next chapter, you will also see it commonly be used in list comprehensions, which is quite useful.

< 4.1 If-Else Statements | Contents | 4.3 Summary and Problems >