Conditional Operator in Python | Python for Data Science | Day 14
Hello, Python squad !
We hope you are staying safe and sound. We are here for you, with all things Python!
In this tutorial, we will be discussing the conditional operator in Python. So, stay tuned with us for the rest of the article to learn about this very useful concept of conditional operator in Python, commonly called ternary operator.
Basically, the conditional operator is the shorthand version, a replacement of the if-else condition code block. The conditional operator bases its result on the condition being True or False. Let’s code a few examples to see how conditional operator is used in Python.
Let’s do a little coding exercise. Write a program to find if a string is lowercase. Your code must be similar to this.
What if we need to boil down this 4 line code to a single line? How can we do this ? The answer is – conditional operator. Look at the code below:
Do you notice how simple the syntax has become? This is the primary reason behind using ternary operator.
Now, let’s look at another way in which we can use the conditional operator.
The syntax is: ( result 1, result 2) [condition]
Result 1: To be displayed when the condition is False.
Result 2: To be displayed when the condition is True.
The code works perfectly fine!
There’s yet another way you can write the conditional operator. We will use the same example as the last two. Check out the code below:
Here. we just write the if – else condition in a single line of code. This does not require any additional explanation. The code is self-explanatory.
You may also read about the ternary operator here: https://realpython.com/python-conditional-statements/
Bravo! We have completed the tutorial on conditional operator. It’s time to test your knowledge through the questions below:
Check out our solutions if you’re stuck.
We have covered 40+ complete Data Science company interviews from the candidates who cracked these interviews.
Data Science Companies interview questions
We also have 30+ e-books on Amazon, Insta Mojo and books which can be delivered directly on your email address
Complete Set of e-books from The Data Monk
Understand some of the very complex topics in Analytics which are asked in most of the interviews
The Data Monk Top Articles
How to become a Data Scientist? Complete study material, free resources and websites to practice
Become a Data Scientist
Make your profile on our website and practice at least 5-7 questions per day. Be a part of ~2000 Analytics expert
Intern | The Data Monk