An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Using ternaries for variable assignment in Python
One of my favorite "tricks" as a programmer is to condense conditional logic (i.e. if/else
blocks) into one line when assigning variables. The ternary operator makes this possible.
If you come from a JavaScript background like I do, you may have seen this done before with a question mark.
const isSuccess = data.response ? true : false
Essentially, this means if data.response is defined we should assign isSuccess the value of true. Otherwise, we'll set it to false.
Recently, I used a ternary operation in Python for the first time. While it, ultimately, works the same way I found the slight difference between languages interesting.
To recreate the snippet above in Python, we could write:
is_success = True if data.response else False
In this case, the right-side of the assignment leads with the "truthy" value, as opposed to the value we're checking. It's not a big difference, but worth noting the difference in API.
The ?
operator has a special place in my heart because I've used it so much. However, Python's ternary operator syntax is probably easier to read for beginners.
Original Link: https://dev.to/ryan_c_harris/using-ternaries-for-variable-assignment-in-python-34p2
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To