Python Basics #2: Variables | Mito

Python Basics #2: Variables

Ready to write Python code 4x faster?

This is post two in our series Python Basics, where we discuss the minimum Python and Jupyter you need to know to successfully automate Excel reports using Mito. Read post one here.

In the last post, we wrote our first piece of code. Now, it's time to understand a few of the basic concepts we used.

Literals

A literal is a specific value. The string "Hello World" in the code above is a literal. We'll often call literals "hard coded" values because the only way to change the value is to actually edit the code.

The idea of literals exists in Excel too. If you open an Excel workbook and type the words “Hello World” into A1, you’ve just used a literal.

Excel supports several types of literals. If we write ="Hello World" in A1 and =5 in A2, we’ll see the words "Hello World" are left aligned whereas the number 5 is right aligned. That’s because Excel knows that "Hello World" is text and 5 is a number.

Just like in Excel, Python literals can be strings, numbers, booleans, etc.

Each of these are example of literals. Just like Excel, Python uses different syntax to define different types of literals. Most importantly, if you want to create a string literal, make sure to put quotes around it!

Variables

A variable is a container that holds a value. You can reference the value using the variable name.

Variables in Python are similar to cells in Excel — both store values and are referenced by their name. If you enter the value “Hello World” into cell A1, you can reference it using the syntax =A1.

Creating a variable

Let's update our code to use a variable.

  1. Create the variable message and set it equal to "Hello World".
  2. Instead of printing the literal "Hello World", print the message variable.

When naming variables in Python, make sure to follow these rules:

  1. No spaces in the variable name. Instead use underscores like this variable_name.
  2. Only use letters, numbers, and underscores.
  3. The first character cannot be a number.

Updating variables

Importantly, a variable's value can change over the course of your program.

In the next post we'll see why the ability to change a variable's value is so important.

Ready to write Python code 4x faster?