How to do an Excel if in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
If-clause in Python are pretty similar to what you could find in excel.
In Excel an if formula would look like this.
=IF(CONDITION, IF_TRUE_WE_DO_THAT, IF_FALSE_WE_DO_THAT)
in Python this translates to
if condition:
if_true_we_do_that
else:
if_false_we_do_that
Example
Let's take the example in which I have two cells, A1 with a value of 2 and A2 with a value of 3.
The idea is to add a logic that returns the max value out of the two cells using if.
In Excel that would translate to
=IF(A1 > A2, A1, A2)
In Python
For the example I do print the values when it fulfills the condition in Python
if A1 > A2:
print("A1")
else:
print("A2")
Here you are, you know now how to do an if in Python.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚