Control Flow

Ternary Operator in Python

The ternary operator is used to return a value based on the result of a binary condition.

It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.


Syntax
result = value_returned_if_true if boolean_expression else value_returned_if_false

Notes

The ternary operator cannot include statements in any of its three parts. It can only include expressions.


Example
def find_maximum(a, b):
    return a if (a > b) else b

Add to Slack

< While Loop   |   Try Catch Block >

© 2018 SyntaxDB. All Rights Reserved.