Lesson 4. Basic Operators in Python


Learning Objectives

  • Explain how operators are used in Python to execute a specific computation or operation.
  • Write Python code to run different operations on data (e.g. arithmetic calculations)

What are Operators in Python?

Operators are symbols in Python that carry out a specific computation, or operation. The value or condition that the operator operates on is called the operand.

The operand can be a variable (e.g. jan_precip_in which has some value, say, 0.70) or data structure like a list (e.g. months). The operand can also be an expression or statement (e.g. checking that list months contains the value January).

There are many different types of operators in Python including:

OperatorUsageExample
Arithmeticto complete mathematical calculationsboulder_precip_in * 25.4
Assignmentto assign new values (typically as a result of a arithmetic calculation)boulder_precip_in *= 25.4
Comparison or Relationalto compare operands (e.g. greater than symbol >)boulder_precip_in > phoenix_precip_in
Identityto check whether operands are the sameboulder_precip_in is not phoenix_precip_in
Membershipto check whether one operand is contained within another operand"January" in months
Logicalto check whether operands are true"January" in months AND "Jan" in months

Arithmetic Operators

In Python, there are many arithmetic operations that can be completed, including operators for:

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • division (/)
  • exponents (**)

Review the cells below and notice that the output is automatically printed without the need to tell Python to display the output.

a = 2
b = 3

a + b
5
b - a
1
b / a
1.5
a * b
6
a ** b
8

For scientific workflows, these arithmetic operators are very useful for converting the units of measurements, for example, from inches to millimeters (1 inch = 25.4 mm) for precipitation values.

The example belows converts the average precipitation value for Boulder, CO in January from inches to millimeters.

jan_precip = 0.70

jan_precip * 25.4
17.779999999999998

Assignment Operators

While arithmetic operators are very useful for calculations, they do not change the original values.

For example, the variable jan_precip continues to store the value 0.7 (the measurement in inches), even after the calculations completed above.

jan_precip
0.7

If you want to assign a new value as a result of a calculation, you can use an assignment operator, which combines the arithmetic operator (e.g. *) with the = to set a new value.

For example, you can combine * and = to multiple a value and set the result equal to itself plus the new value.

jan_precip *= 25.4

Recall that on the previous page on working with lists, you also used an assignment operator to add items to the end of a list.

This is a special case of the addition assignment operator += because it is not actually completing a mathematical operation on the list. It simply adds the values as new items to the end of the list.

months = ["January", "February"]

months
['January', 'February']
months += ["March", "April"]

months
['January', 'February', 'March', 'April']

However, not all assignment operators can be used on all object types. For example, the following code will result in an error because lists cannot have mathematical operations executed on them.

boulder_precip_in = [0.70, 0.75, 1.85]
boulder_precip_in *= 25.4

You can review the Python docs on types and operations to see what kinds of operations can be run on different object types.

Notice now that the output is not automatically printed.

jan_precip = 0.70

jan_precip *= 25.4

To see the new value, you can call the variable name (e.g. jan_precip), or you can use the print statement (e.g. print(jan_precip)) to display the new value.

Using the print statement can be very helpful because then you can print multiple values.

For example, notice calling only the variable names (e.g. a, jan_precip, b), you are only shown the value of the last variable.

a
jan_precip
b
3

Using print(), you can print as many things as you want.

print(a)
print(jan_precip)
print(b)
2
17.779999999999998
3

You can even combine the variables with a text string in a print statement by including a text string "text" within the print statement.

To do this, simply separate the text string from the object that is being printed using a comma ,.

print("January precipitation:", jan_precip)
January precipitation: 17.779999999999998

Notice that the word print does not show up the output. Instead, you simply see the result, without the parentheses or quotations for the text string.

You have now deliberately used your first **Python function!** Functions in Python are commands that can take inputs that are used to produce output.

You will learn more about functions later in this textbook, and you will use the print function a lot, as it can be very handy for viewing results and for communicating the status of your code.

Practice Your Python Skills

Data on average monthly precipitation for Boulder, Colorado provided by the U.S. National Oceanic and Atmospheric Administration (NOAA).

MonthPrecipitation (inches)
Jan0.70
Feb0.75
Mar1.85
Apr2.93
May3.05
June2.02
July1.93
Aug1.62
Sept1.84
Oct1.31
Nov1.39
Dec0.84

Test your Python skills to:

  1. Create new variables for monthly average precipitation values (inches) for Boulder, CO for January through December.

  2. Use the appropriate arithmetic operator to convert the monthly variables for jan to dec from inches to millimeters (1 inch = 25.4 mm).

  3. Create a list that contains the converted monthly average precipitation values in millimeters. Print your list (hint: print(list_name)).

  4. Create a list that contains the month names from the table above.

[17.779999999999998, 19.049999999999997, 46.99, 74.422, 77.46999999999998, 51.308, 49.022, 41.148, 46.736, 33.274, 35.306, 21.336]

Challenge Your Python Skills

Modify the following code to create a plot of your data:

# Import necessary plot package
import matplotlib.pyplot as plt

# Plot monthly precipitation values
fig, ax = plt.subplots(figsize=(10, 10))
ax.bar(listname_months, listname_precip, color="blue")
ax.set(title="Add plot title here.",
       xlabel="Add x axis label here.", ylabel="Add y axis label here.");

Customize this plot by:

  1. Replacing listname_months and listname_precip with the names of the lists that you created.
  2. Change the color of the plot to aqua.
  3. Update the text for the titles and axes labels.
  4. Modifying the values in figsize=(10, 10) to change the size of your plot.

For your titles and labels, be sure to think about the following pieces of information that could help someone easily interpret the plot:

  • geographic coverage or extent of data.
  • duration or temporal extent of the data.
  • what was actually measured and/or represented by the data.
  • units of measurement.

Leave a Comment