Hour 5. Using Arithmetic in Your Programs
What You’ll Learn in This Hour:
Using basic math
Working with fractions
Working with complex numbers
Using the math module in Python scripts
Using other Python math libraries
Just about every Python script that you write requires some type of mathematical operation. Whether
you need to increment a counter or calculate the Fourier transform of a signal, you need to know how
to incorporate mathematical operators and functions in your Python code. This hour walks through all
the basics you need to know to work with numbers and perform calculations in your Raspberry Pi
Python scripts.
Working with Math Operators
Python supports all the basic math calculations that you’d expect from a programming language. This
section walks you through the basics of how to use math operators in your Python scripts.
Python Math Operators
To get a feel for how Python handles numbers, you can open an IDLE window and experiment with
some simple math calculations right at the command line. You can use the IDLE command prompt as a
calculator, entering any type of mathematical equation for it to evaluate and return an answer.
Here’s an example of some basic math calculations performed in IDLE:
>>> 1 + 1
2
>>> 5 - 2
3
>>> 2 * 5
10
>>> 15 / 3
5.0
>>>
As you can see, Python supports all the basic math operators that you learned in school (using an
asterisk for multiplication and a forward slash for division).
By the Way: Division Data Types
Notice that when we performed the division, Python automatically converted the output
to a floating-point data type, even though the inputs were both integers. This is a new
feature in Python v3.2!
Besides the basic math operators that you were taught in elementary school, Python also supports