- 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
There are many different types of operators in Python including:
|Arithmetic||to complete mathematical calculations|
|Assignment||to assign new values (typically as a result of a arithmetic calculation)|
|Comparison or Relational||to compare operands (e.g. greater than symbol |
|Identity||to check whether operands are the same|
|Membership||to check whether one operand is contained within another operand|
|Logical||to check whether operands are |
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
b - a
b / a
a * b
a ** b
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
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.
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
= 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
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 mathmematical 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.
b), you are only shown the value of the last variable.
a jan_precip b
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
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
Practice Your Python Skills
Data on average monthly precipitation for Boulder, Colorado provided by the U.S. National Oceanic and Atmospheric Administration (NOAA).
Python skills to:
Create new variables for monthly average precipitation values (inches) for Boulder, CO for January through December.
Use the appropriate arithmetic operator to convert the monthly variables for
decfrom inches to millimeters (1 inch = 25.4 mm).
Create a list that contains the converted monthly average precipitation values in millimeters. Print your list (hint:
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:
listname_precipwith the names of the lists that you created.
- Change the color of the plot to aqua.
- Update the text for the titles and axes labels.
- 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.