Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

The 1 Definitive Guide to Python in Excel

Welcome to the definitive guide to Python in Excel. Whether you are new to Python, new to Excel, or both, this guide will make you an expert. We have 33 chapters, and over 40 examples to uncover all the beauty of Python in Excel.

I am Alessandro Maggio, a Program Manager who uses (and loves) Excel a lot. We really, truly, deeply needed Python in Excel: finally Microsoft made us happy. I was feeling like this when this was first released in August 2023, and I hope you feel the same for this guide.

Most data analysist asking Microsoft to release Python in Excel.

Stick to the end to connect with me on LinkedIn!

If you are familiar with both Excel and Python ad you are in a rush, click here now for the quick-start section of the guide.

We have a lot to cover, so here’s the table of content.

  1. Introduction to Python in Excel
    1. What is Python in Excel?
    2. Advantages of Python in Excel
    3. Get started in under 1 minute with Python in Excel
  2. How to use Python in Excel
    1. Enabling Python in Excel
    2. How does Python in Excel work?
    3. The =PY() formula
    4. The xl() function to access Excel data
    5. Accessing tables with xl()
    6. Python output vs. Excel value
    7. Handling errors
    8. Cross-referencing objects
  3. Python Crash Course
    1. Algorithmic logic
    2. Variable assignment
    3. Conditional statements
    4. Loops
    5. Collections
    6. Dictionaries
    7. Functions
    8. Classes
    9. Try-Except
  4. Advanced Python in Excel
    1. Initialization and shared libraries
    2. Pandas dataframes in Excel
    3. Using matplotlib in Excel
  5. Conclusion
    1. Privacy Considerations
    2. What Python in Excel can’t do
    3. Alternatives to Python in Excel
    1. Additional resources
    2. Connect and get help

Introduction to Python in Excel

What is Python in Excel?

Microsoft Excel is a productivity software that helps you to arrange data in tables, manipulate, and analyze them using formulas. People and businesses of all sizes use Excel to produce financial forecasts, do expenses reports, plan projects, estimate how many products they need to sell, and so on.

Until August 2023, Excel had a big problem. Excel did not support advanced programming logic to elaborate data. This was really a shame, because what you could do with simplicity and just a few lines of codes in any programming language required nasty arcane formulas in Excel. Even Visual Basic for Applications (VBA), the programming language native in Excel, could not compare to modern programming languages.

Enters Python. Python is a powerful language, simple, easy to learn, and with a lot of built-in modules for data analysis and presentation. It quickly gained popularity with data scientists, software developers, and any profession that is even remotely related to coding. Wouldn’t it be amazing if we can combine the power of Python in elaborate data with the power of Excel to arrange, structure and get data? Now, we can.

August 22, 2023 marks history for any business consultant. This is when Microsoft released Python in Excel (in preview mode). Since this date, all Microsoft 365 subscribers – both personal and business – can use Python in Excel. That is, you can write Python code in Excel formulas, and Excel will interpret it correctly. You can even use Python to plot charts inside Excel!

If you worked in Excel at a professional level, this should get you excited already. If not, you either haven’t worked enough with Excel to feel the pain of a lack of Python, or you don’t fully grasp the power of Python just yet. This is what the next section is for.

Advantages of Python in Excel

With Python in Excel, you can do the same things you were doing before without it. That is, you can do the same analysis and produce the same outcome that you used to do in the past. Maybe, now you can achieve some slightly better presentation, as in better aesthetic of charts. What’s all the fuss about then?

The power of Python in Excel is that you can do things significantly faster than with either native Excel formulas or with VBA. And I don’t mean the computer is faster, I mean you are faster to create the analysis. This is because Python code is much cleaner to read than Excel formulas. After all, Excel formulas were designed to be crammed in a cell within Excel. Python code was designed to write real software, and to have entire files purely written in Python.

All this translates into a set of clear advantages over traditional Excel, even considering when you have VBA macros enabled.

  1. Python code is easier to read, troubleshoot and debug than Excel formulas. This means you can add more complex logic without blowing up your file.
  2. Python code is much faster to write than VBA code, it has a larger online community and support all features of modern programming languages, such as classes. This means your logic can quickly become super-advanced without unnecessary complexity.
  3. You can use Python to create plots and write Python code to define the appearance of those charts (colors, sizes etc.). This means the style is much more portable from one chart to the next, or even between different files.
  4. If you already know Python, you don’t need to spend extra time learning how to do the same thing in Excel or VBA. Since Python is easy to learn, even if you don’t know Python, it will be easier to learn it rather than memorize a lot of Excel formulas.
  5. Python in Excel is natively enabled, and you just need a formula to use it. This is different from VBA, where you first need to change the file extension from XLSX to XLSM, enable Macros, and then open a VBA editor that still feels like Windows 95.

But having Python in Excel is not only better than having Excel without Python. It is even better compared to creating your own Python scripts outside of an Excel file, and for multiple reasons:

  1. Python in Excel runs on Microsoft servers, and not on your computer. So, you don’t need to spend time setting up an environment which then does not work if you move your file to another computer.
  2. You can just write Python code inside Excel cells and access all the data you have in the file. No need to spend time importing and parsing the Excel file.
  3. You can mix Python with Excel formulas already present in Excel.
  4. You can work with Python while you work in Excel. Without this, you either have your Python script editing your file, or you opening and looking at in in Excel, not both at the same time.

Hopefully, this convinces you that having Python in Excel is a quantum leap forward. No reason while you would not learn it, so let’s get started!

Get started in under 1 minute with Python in Excel

If you are already familiar with Python and already familiar with Excel, you can get started in under 1 minute. If you are new to either (or both), you may struggle to read through this section. Don’t worry, we have a more detailed guide moving forward (worth reading even if you are an expert).

Python in Excel is currently in preview mode, so it means it is not enabled by default. You need to have an active subscription to Microsoft 365, and have preview mode enabled. If you don’t have and don’t want Microsoft 365, scroll at the end of this guide for alternatives. If you do, but don’t have preview mode enabled, read “Enabling Python in Excel” just a few paragraphs below.

Okay good, now you have Python in Excel enabled. How do you use it? Simply put, use the PY Excel formula to write any Python code in it.

=PY()

Note that normal formulas start and end with brackets. Python, however, changes how Excel interprets the cell. So, once you write =PY( you can start writing code, and instead of closing brackets you hit Ctrl + Enter to complete.

Inside Python in Excel, you can use the xl() method to access Excel ranges. Those are returned as Python values for individual cells, or lists for arrays and ranges. This method accepts one string parameter, the definition of the range you want to fetch, for example:

xl(“A1”)
xl(“Sheet2!B5:C8”)
xl(“my_table[My_header]”)

Combine this inside the PY function to write some Python logic, for example this will return the value of A1 multiplied by 5, and will fail if A1 is empty (rendered as “None” value into Python).

=PY(xl(“A1”) * 5)

You can write multiline statements inside your PY function, use if-else logic, loops, and even functions, classes, and some external libraries that Microsoft makes available for you (like pandas and matplotlib).

The PY function returns to Excel the value of the last statement and displays that in the cell. For example, the following script will return the value “Hello John!”.

=PY(
full_name = “John Doe”
first_name = full_name.split()[0]

“Hello “ + first_name + “!”
)

You can use variables and names you define in another =PY() function in another cell. Since Excel will process this top down, define any file-wide Python code (such as constants) in the cell A1 of the first sheet of the file.

With this, seasoned Python professionals with some Excel understanding should be good to go and explore the power of Python in Excel. Yet, going through the full guide will uncover all the secrets that Python in Excel has to offer. Let’s get started!

How to use Python in Excel

Enabling Python in Excel

The first step we need to do is to check if Python in Excel is Enabled. You can do that by writing =PY(1) in any cell in any Excel file. This will show “1” in the cell if Python is enabled, or will show an error if not. If you see the number “1” in your cell, you are good and you can proceed to the next section. If not, keep reading here.

Write this code inside the =PY() function, if it works you should see this stack icon. If not, you will get an error and need to enable Python in Excel.

Note that this may require a few seconds, during which the #BUSY error is displayed (as Excel is sending your Python code to Microsoft’s servers).

Let’s assume this is not working: it means Python in Excel is not enabled. First, you need to be sure you have Microsoft 365 with an active subscription: a lifetime license for your PC, for example Office 2019, is not good enough. After all, Microsoft is giving you their servers for your computations every time you need them, so a subscription model makes sense. You can check if you have an active Microsoft 365 subscription by going into File > Account. You are looking to see if you have a “Microsoft 365” subscription here.

Check if you are subscribed to Microsoft 365 there.

If you have, and yet Python in Excel is still not working, it means this feature is still not available as a mainstream feature in your country. You can enable it by opting in for the beta preview, which means you will get new features faster (even if they might be buggier in the beginning). From the same screen, go in Microsoft 365 Insider and then Change Channel.

Change channel to get beta updates.

Here, you need to select the Beta Channel and tick all boxes. Once you are done, click OK, and you will download some updates and may need to restart Excel.

Beta channel get new updates faster, even if they are still being tested.

Once all this is done you will have Python in Excel completely enable and ready to go.

How does Python in Excel work?

Before we start writing Python code inside Excel, let’s spend a few seconds to understand how this works under the hood. It will make future troubleshooting much easier.

Microsoft decided to use Anaconda as the underlying engine, instead of vanilla Python. This means you will write Python code, which will be interpreted by Anaconda. Anaconda supports all native functionalities of Python, plus it has some additional features and better performance. All this is transparent for you, what this means is that you write Python code, and it “magically” gets executed.

The real point to keep in mind is that the Anaconda engine is not on your computer, but on Microsoft’s servers. So, whenever you write Python code, the code that you write is sent to the Microsoft’s servers in some datacenter for them to elaborate it. This along with the data it needs to elaborate that are part of the file. This means you need a constant Internet connection if you want to use Python in Excel.

Saying we send data to Microsoft servers is imprecise. In reality, it is not like data is on your computer and it gets sent to Microsoft. Your file is already in OneDrive as part of Microsoft 365, so the data is already there, and Microsoft just needs to process it, rather than simply storing it.

Other than having constant internet connection, it means some elaborations may require a few seconds and will not appear immediately. When this happens, you get the #BUSY error to indicate Excel (and Microsoft’s servers) are busy processing your request, and you should expect some result soon, as long as you remain connected.

The =PY() formula

“PY” is short for Python. In fact, if you write some Python file (regardless of Excel), its extension is “.py”, much like a Word document will be “.docx”. This =PY() formula in Excel allows you to write Python code, and it works differently from any other formula you might have seen so far.

To use this formula, you write in an empty cell not containing anything else, and you simply write =PY and then open a bracket (thus writing =PY()). This will tell Excel that this specific cell will contain Python code, and not Excel formulas. You can see the difference in the input box, because it is marked with a “PY” statement next to the text.

This PY note indicates you can write Python code in this cell.

When you complete a normal formula in Excel, you need to close the bracket you opened. Not in this case. With PY, you simply write Python code, and when you are finished you hit Ctrl + Enter. This will finalize the code you wrote, and will send it to the Microsoft servers for elaboration.

Inside, you can write any Python code that you want. If you are unfamiliar with Python, in the next chapter of this guide we will teach you all the basics of Python you need. For now, let’s try to follow along with this example.

We assign two variables, multiply them by each other, and show the result.

We wrote a 3-line piece of Python code, using two variables: a and b. Variables are just “things with a name” that act as a container for values. The value they contain may change over time. In this case, we put the value of the number 2 inside a, and the value of number 3 inside b. Then, we execute the multiplication between a and b. Since this is the last statement that gets executed, this is what Python will return. For your convenience, here is the exact Python code we wrote in Excel:

a = 2
b = 3
a * b

As you saw in the previous picture, this code returns the value of 6, which is the product of 2 * 3 (the current values of the two variables).

The xl() function to access Excel data

Python in Excel is powerful, but it would be useless if it can’t access or read data from other cells. Of course, it can, we just need to use the proper function.

Inside any Python in Excel code, we can use a special xl() function that Microsoft makes available. This function wants to know an Excel range, such as the name of a cell or group of cells, then go get the value of that cell. The easiest way to use it is starting with the name of the cell we want to target. For example, we can rewrite the previous example to get the value of a and b from two cells (A1 and B1 in this case), instead of statically writing the values inside the Python code.

The xl() function allows us to reference cells, tables and ranges in our Excel file.

As you can see here, Excel colors “A1” and “B1” of blue and red respectively, both inside the Python code and in the cells in the spreadsheet. This is to show you that references are working, and Excel is indeed getting the value from those cells. As before, the result of this code, which we copy below for more convenience, is 6.

a = xl("A1")
b = xl("B1")
a * b

Note the syntax of xl() function. It needs a parameter, an input to provide within the brackets. That input is the name of the range we want to target, and it is a Python string (which simply means piece of text). To make Python understand we are just providing a piece of text rather than other Python code, we quote it. In this way, Python knows everything between quotes will just be a piece of text and must be treated like so.

But xl() does not have to reference just a cell. It can reference a range of multiple cells, either a row, a column, or a matrix. In this example, we reference an entire matrix.

Find the max in a range using Python in Excel

For your convenience, here is the code we used in this example. This fetches the maximum value of the matrix. Or, more correctly, it first find the maximum value of each column, and then finds the maximum value among those (this is why we use .max() twice). The result, based on this data, is 20.

xl("A1:F7").max().max()

You can use the mouse to apply a range to the xl() function. If you are starting to type inside a PY block of code in Excel, and your cursor is inside that cell, then you can click on any other cell with the mouse. If you click on cell C4, for example, it will automatically add xl(“C4”) to your Python code where your cursor is. If you select a larger range, for example A1 to F7 (you can do that by clicking on A1 and then using arrow-down and arrow-right while holding shift), it will add xl(“A1:F7”). As you move with the arrows to expand or reduce your range, the output will change to reflect the range you are selecting.

What does the xl() function return? Primary values, or Pandas Dataframes. Whenever we use the xl() function, it gives us back a value. If we are using xl() to select a single cell, it will give us back the value of that cell. That can either be a number (integer or floating point), a string (piece of text), or “None” (a special Python value to indicate there is no value).

However, when we return a range that contains multiple cells, we get a Pandas Dataframe. Pandas is an additional module available in Python to manipulate data, very popular among data scientists. A dataframe is just a “table-like” structure in Python, that comes with nice features that Pandas provide. For example, as we have seen, it has a quick way to find the maximum value, but also minimum, average, and so on. Just know this for now, we will see more on Pandas when we get to Advanced Python in Excel later in this guide.

Accessing tables with xl()

In Python in Excel, you can use the xl() function reference any range. That may be a range of cells defined by cells names, an entire row or set of rows or columns, a named range in the Name manager, or a table. In other words, you can reference any part of Excel much in the same way as you would with a normal Excel formula.

Particularly, we have two options for tables. On one side, we can simply use the table name, on the other we can use the table name with [#All] notation. Let’s go in order.

In this example, we simply refer to the table (shown in the picture) that is named products. We just use the standard xl() formula and we reference the table by name.

xl("products")

Once you write the code and hit Ctrl + Enter to submit it, you will see there is an icon in the cell that contains the Python code. This icon represents a stack, or set of layers one on top of another. That’s the one highlighted in red. If you click that, it will open a tooltip that will show you what is the Python value we are returning, as an Excel cell cannot show complex data structures by itself. In this example, you see we are getting all the values in the table but we don’t have information about the headers (which are just replaced by numbers).

This is how we can reference a table using xl(), note that we are not getting column names.

If we want to get also header names, we need to use the notation [#All] to tell Excel to include also the headers. However, since now the first row is not part of data, but it represents the header, we want to be sure Excel understands that. So, we provide the additional parameter “headers” and set it to True. In this way, Python in Excel will know that the first row is to be used to name the columns.

xl("products[#All]", headers=True)

Indeed, if we hover on the stack icon next to the cell, we will see the headers of the dataframe instead of the numbers.

If we search for all items and set headers to True, we can see headers in the dataframe.

If we don’t set the headers to True in the xl() function, then Excel will just assume the first row is part of the dataset. As a result, we would get the numbered columns as before (1, 2, and 3), and have as first row the header (sku, status, price).

Python Output vs. Excel Value (Return Arrays and Matrixes)

In the previous example, we saw that we are targeting with xl() an entire table. However, in the cell where we write Python in Excel code, we do not see the entire table returned, but just a piece of text “Dataframe”. What if we want to return the entire table, and display it in multiple Excel cells?

With traditional Excel, we can do something similar using array formulas, special formulas that instead of returning a value return a list of values. If they return those values in the shape of a column, then all the cells below the one where you write the formula are populated with this content. If your array formula returns a row, all the cells to the right of where you wrote the formula will be populated. And, if it returns a matrix (columns and rows), Excel will populate to the bottom and to the right. Of course, the cell where you write the formula is always populated and acts as the first item in the list.

With Python in Excel, we can do something similar. We have a way to display Python dataframe across multiple cells in Excel. To do that, we simply need to change the return type.

Let’s take the example from the previous section. Next to the box where you type your Python in Excel code, you have a dropdown where you can select if you want your return to be a Python object or an Excel value. By default, it is going to be Python object, but you can change it.

Change the output to Excel value to render the output across one or multiple cells.

Once you do that, you will see that the return expands to show the entire table, and populates it across multiple columns and rows.

This is the Excel value output.

If you have your cursor in the cell where you wrote the Python formula, note that Excel will highlight in a box all the cells that are getting a value because of this formula. In our case, cells from A9 to C13 are affected. And, as you can see, the stack icon to represent the Python object is not there anymore. This seems like any normal array formula in Excel now, except it is running Python in Excel natively.

Handling Errors

Python in Excel brings a new set of errors that were not present in traditional Excel. It is worth dedicating some time to understanding them.

The first new error in Python in Excel is #BUSY. If you get this in a cell, it means Excel and Microsoft servers are busy running your computation. You just need to wait, this is a transient issue and not lasting much – except to have this error for a few seconds every time you write new Python code, or every time you refresh data that warrant a re-computation by Excel.

#BUSY means Microsoft servers have accepted your request and are processing it, you have an open communication with them. In other words, if you have connectivity problems, it is not #BUSY the error you will get (you will get #CONNECT instead). Overall, as this is a transient error and it is part of the nature of Python in Excel, it is not worth spending time troubleshooting it.

The most important error in Python in Excel is #PYTHON. When you get this error, it means there is something wrong in your Python code. You may have a typo, or some other form of faulty logic that is preventing your code from working. In this case, I recommend doing two things for troubleshooting:

  1. Use a Try-Except block to return the error to Excel, set the return type to Python object and over the stack icon to see the content of the error (if you are unfamiliar with Python errors or Try-Except, they are explained later in this guide).
  2. Copy your Python code into a separate python file, run it on your computer (outside of Python in Excel) and debug using a proper coding editor, such as Visual Studio Code or PyCharm. To do this, you will need to mock the xl() method. That is, created a “fake” xl() method that returns what you need. This is more advanced troubleshooting, reserved for real programmers.

Cross-referencing objects

In Python in Excel, you can reference other Python objects such as dataframes from your Python code inside the =PY() formula. This can become helpful to do advanced data manipulation. To say it even simpler, if you return a Python object in a cell, another cell with Python code in it can take that object and read it.

Let’s take the table example we have been working on in the past few sections. Here, we switch back our original return in A9 to Python Object (rather than Excel value). At this point, we go in another cell, A12, and write the Python code with =PY() to reference the A9 range. Note that the A9 range contains the Python dataframe that represents the entire table. In A12, we set the return type to Excel value, and voilà. We have returned the table as Excel value, not by referencing the table directly, but by referencing the dataframe.

Here, we store the Python object in cell A9, and then write in cell A12 a reference just to that, but rendering it as Excel value instead.

This is useful, because we can add multiple intermediary steps that reference dataframes or other Python objects, extending the functionality of Python in Excel.

Python Crash Course

If you want to use Python in Excel, you need to know how to use Python in the first place. That is one of the easiest programming languages to learn, if not the easiest altogether. If you are not already familiar with it, you can learn python today in this course. In fact, we have two options for you.

If you have more time (about 1 day, or 8 hours), take our ultimate (and free) Python course. This will assume anything, will start from the very basics and will build with several lessons bringing you to quite advanced concepts. It is completely free, and as a bonus you will know Python not only in Excel, but in general.

Instead, if you are in a rush and want to learn Python specifically for Excel, keep reading here. This section will give you all the tools you need to work effectively with Python inside Excel. Here, we will not install Python in your computer, but test everything inside Excel, thanks to Microsoft’s servers running the code for us.

Algorithmic logic

Python is a programming language, and just like any other programming language it relies on algorithmic logic. This is a type of logic, or approach to problems, where you define tasks as a set of repeatable steps. An algorithm is nothing more than a specific set of instructions with no ambiguity and that can be repeated in the exact same way.

We normally represent algorithms as flow-charts, because this logic is generic and not specific to Python: it can be implemented with any programming language. A classic example of this is a cooking recipe. After all, a cooking recipe is a set of steps to execute in a specific order. Let’s make an example with the recipe of a boiled egg.

To make a boiled egg, you have to make the water boil, and then put your egg inside of it and cook it for 4-5 minutes if you want it dippy/creamy, or 6-7 minutes if you want it more solid (according to BBC good food). How can we translate into an algorithm? Let’s put this series of steps into an algorithm flow chart. In such flow charts, start and end are ellipses, while tasks are rectangles.

A simple algorithm as a sequence of steps.

This is not very deterministic if we think about it. What does it mean “boil water” after all, how long should it boil? Different people may interpret this differently, and the same is true for “cook egg”. We can be more specific with times, and also insert conditional logic: execute parts of the flow chart based on a decision we make. In this case, the decision is whether we want dippy or solid egg. If we want it dippy, let’s cook it for 4 minutes, if we want it solid let’s cook it for 6. In flow charts, decisions are represented by diamonds.

Conditional logic (choices) in the algorithm.

We can make this flow chart even better. In fact, if you think about it, we don’t want to put the water on max heat for 10 minutes. What we really want is to put it on max heat and then wait until it boils. How can we do that? With an algorithm, we simply need to have a decision “Is the water boiling?” and, if yes, we proceed. If not, we go back to a previous step, in this case waiting for some more. After we waited some more, we check it again, and if it is still not boiling we wait again. This is a loop, a part of the algorithm that repeats itself.

Adding a loop to our algorithm.

Now we have a solid algorithm, a set of steps that you can easily repeat over and over. As we will see in Python in Excel, but really with any programming language, instead of drawing a chart we simply write code. That is, we transform this flow-chart in a set of written instructions that the computer can understand. And, of course, we do that we things the computer is able to do, such as making calculations (rather than boiling eggs).

We chose this example of boiling egg because algorithms are a form of logic. You can apply them to any problem in life, not exclusively in computer science or Excel.

Variable assignment

The first thing you need to learn to be proficient in Python in Excel is variable assignment. Like any programming language, python has the concept of variable.

A variable is a placeholder, a container that will hold some sort of value into it. The value it holds may change whenever we run the program, and may even change during the same execution of the program (depending on how we structure it). To create a variable, you just type a name, starting with a letter and containing letters, underscores, and/or numbers. You also need to assign a value to it when initializing, that is, you need to tell what the variable will contain.

In a simple example, we can create a variable named “my_variable” that contains the number 5 and another variable named “my_other_variable” that contains the number 10. To assign a value to a variable, we use the equal (=) operator. If we return the value of my_variable in Excel, we will see 5.

my_variable = 5
my_other_variable = 10
my_variable
Assign variables in Excel using the equal sign.

The concept here is simple. Whenever we use the name of the variable, Python will replace it with its content during execution. This means if we make a multiplication of the two variables that we have, we will get 50.

my_variable = 5
my_other_variable = 10
my_variable * my_other_variable
You can use variable names instead of their values to make your code more reusable.

The advantage of this approach is that if you have complex operations you do not need to hardcode all the values inside the operations. Instead, you can use variables and define the values at the beginning of your problem, or more easily import data from Excel (with the xl() function) and store them into variable.

You can reassign the value of a variable, that is, you can put a new value into a variable after you define it. That may be another static value, or the value you get as a result of an operation. In this example, we overwrite the value in my_variable. Before, it was 5, now it is 52 (the result of this operation). The possibility to change the value inside variables enables quite complex logic.

my_variable = 5
my_other_variable = 10
my_variable = my_variable * my_other_variable + 2
my_variable
You can override the value of a variable simpl re-assigning it.

Variables don’t have to contain numbers. They can contain strings (pieces of text, delimited by quotes), integers, decimal numbers, and they can even contain a list of values. In case we want to provide a list of values, we need to enclose this list within square brackets, and separate each value with a comma (we can use either static values or other variable names in those lists).

This variable is a list of values, we can show it in Excel if we set the output to Excel value.

Note that in this example we set the return value to Excel value so that we can see all the items in a list. As you can see, Excel returns them in a column, one after another. We will see how to manipulate lists better when we will cover loops, later on in this guide.

Conditional statements

Conditional statements are a powerful tool in Python in Excel that allows you to execute part of your algorithm on certain conditions. We can think of these statements as “if this condition is true, do this, otherwise do this other thing”. In fact, writing conditional statements in Python is not that different from writing this sentence.

To write a condition, we need to use the if keyword, write the condition that we want to check afterward and add a colon at the end of the line. Then, any subsequent line that is indented below this conditional statements will run only if the condition is true.

input = xl("A1")
result = "Less than 3"

if input >= 3:
   result = "Greater than or equal to 3"

result
Conditional statement, override the result only if the input is greater than or equal to 3.

In this example, we load the value in the cell A1 into a variable, then we check if that variable is greater than or equal to 3. If so, we overwrite the result. If not, we leave the result in its original state, and then we show the result in any case (outside of the indentation).

We can also combine multiple conditions in a single statement. In that case, we use the and keyword to join two or more conditions, all of which must be true at the same for the overall condition to return true. We can also use the or keyword, in which case the overall condition will return true if at least one of the joined conditions is true. We can combine multiple keywords with brackets, and even negate conditions using not. To summarize:

  • true and true returns true
  • true and false returns false
  • false and false returns false
  • true or true returns true
  • true or false returns true
  • false or false returns false
  • not true returns false
  • (true or false) and true is equivalent to true and true and returns true

The and, or, and not keywords are called binary operators because they work with binary or Boolean value, items that can have only two values (true or false) and are thus called binary.

input = xl("A1")
result = "Not within 3 and 15"

if input >= 3 and input 


This post first appeared on ICTShore.com, please read the originial post: here

Share the post

The 1 Definitive Guide to Python in Excel

×

Subscribe to Ictshore.com

Get updates delivered right to your inbox!

Thank you for your subscription

×