Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

Does Python have a ternary conditional operator?

Solution:

Some programming languages use the ternary operator to reduce if-else code blocks, but does Python allow this syntax? If this is the case, what is the structure of a Python ternary operator?

The ternary operator reduces the amount of code required to create if-else blocks.

The syntax of ternary operators varies by language, but in most situations, the operator deals with three arguments: the comparison, the result is true, and the result is false.

A standard if-else block requires at least four lines of code.

For example -


  if x > y
  z = x
else:
  z = y

The ternary operator condenses an if-else statement into a single line of code.

How? 

Here’s a syntax.


  x if condition else y

The operator tests a condition and returns x if it is true or y if it is false.

Here’s an example.


x = 10
y = 5

z = x if x > y else y

print("z = " + str(z))

Output: 

z = 10

If x is bigger than y, the ternary operator above assigns the value of x (10) to the variable z.

Want to know more about Python? Check out our blogs!