Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22875

Python Morsels: Python's ternary operator

$
0
0

Python doesn't have the traditional ternary operator that most programming languages do. Instead we have "conditional expressions".

Python doesn't have typical ternary operators

Here we have an if-else statement:

ifamount==1:noun="item"else:noun="items"
ifamount==1:noun="item"else:noun="items"

Many programming languages allow you to take code like this, that assigns a variable to one of two values based on a condition, and turn that into a single line of code:

noun=amount==1?"item":"items"
noun=amount==1?"item":"items"

That strange ?...: syntax is often called a ternary operator.

Python doesn't support that syntax: that isn't valid Python code. Instead, we have something called a conditional expression.

Python's conditional expressions (a.k.a. inline if)

Python's conditional expression looks like …

Read the full article: https://www.pythonmorsels.com/ternary-operator/


Viewing all articles
Browse latest Browse all 22875

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>