How to do an Excel if in Python

1 min

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)
IF condition in Excel

in Python this translates to

if condition:
	if_true_we_do_that
else:
	if_false_we_do_that
A if clause that looks like an excel if

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)
IF clause in excel that returns the biggest value

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")
A if clause that looks like an excel if

Here you are, you know now how to do an if in Python.