In this section, we will cover how to do math in Python. In Python,
there are several built-in math operators that we can use to perform
calculations. These include:
- Addition
+
- Subtraction
-
- Multiplication
*
- Division
/
- Exponent
**
- Parentheses
( )
- Assignment
=
Python also follows the rules of PEMDAS: parentheses, exponents,
multiplication, division, addition, and subtraction are performed in
that order, from left to right.
It's important to note that the single equal sign does not check if the
two sides are equal, but rather assigns the value of the expression on
the right side to the variable on the left.
Finally, let's take a look at an example of how to use these operators
in a program to calculate the area of a trapezoid:
# area of a trapezoid
base1 = 10
base2 = 8
height = 20
area = height * (base1 + base2) / 2
print(area)
# 180
In this program, the values of base1
and base2
are first added together to get 18 since they are in the parentheses.
That value of 18 is then multiplied by height
and divided
by 2, in order from left to right. The resulting value of 180 is then
assigned to the variable area
and printed to the console.