Arithmetic Operators and Built-in Functions

Using Python as a calculator

The following are examples of the kinds of Python expressions that we can use.

In [1]:
4 + 5
Out[1]:
9
In [2]:
15 - 12.5
Out[2]:
2.5
In [3]:
3.4 * 6
Out[3]:
20.4

Each Python value has a type. 4, 5, 15, and 6 have type int. 12.5 and 3.4 have type float. Float stands for floating point number. Floats are approximations to the real numbers.

Python has two different division operators: / produces a float and // is integer division (it produces an int).

In [4]:
8 / 4
Out[4]:
2.0
In [5]:
8 // 4
Out[5]:
2
In [6]:
# When writing programs, we can put in English language explanations called comments.
# Whatever comes after the # symbol is not executed.
In [7]:
2 ** 5  # 2 to the power of 5
Out[7]:
32
In [8]:
# The % operator gives the remainder of a division.
# 10 % 3 gives the remainder of 10 // 3
10 % 3
Out[8]:
1

In other words, the fraction 10 / 3 can be rewritten as 3 1/3, so the remainder is 1.

Operator order of precedence (from highest to lowest)

**

- (negation)

*, /, //, % (left to right)

+ (addition), - (subtraction) (left to right)

Encountering Errors

When programming, it is common to encounter errors. You will learn how to interpret the error messages, so that you can fix your code. Here are a few examples:

In [9]:
3 + 
  File "<ipython-input-9-4715fb1d5390>", line 1
    3 +
        ^
SyntaxError: invalid syntax
In [10]:
4 + 5 ) * 2
  File "<ipython-input-10-9753380d8def>", line 1
    4 + 5 ) * 2
          ^
SyntaxError: invalid syntax
In [11]:
2 * * 5
  File "<ipython-input-11-b1206b14b483>", line 1
    2 * * 5
        ^
SyntaxError: invalid syntax
In [12]:
9 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-12-263dd5d0c9f7> in <module>()
----> 1 9 / 0

ZeroDivisionError: division by zero

Practice Exercise: Writing expressions

  1. A patient just turned 80 years old. Write a Python expression to calculate her age in months.
  2. A father reports that his son's temperature was 40.1 degrees Celsius when measured at home. Write an expression to covert the temperature from Celsius to Fahreneheit. (Formula: Multiply by 9, divide by 5, and then add 32.)

Built-in Functions

In addition to the operators shown above, the Python language comes with a set of functions that we can use.

In [13]:
min(45, 23)
Out[13]:
23
In [14]:
max(5.5, 5.52)
Out[14]:
5.52
In [15]:
abs(-10)
Out[15]:
10
In [16]:
abs(-4 - 8)
Out[16]:
12
In [17]:
type(4)
Out[17]:
int
In [19]:
type(8.25)
Out[19]:
float

Practice Exercise: Calling on round

Python has a built-in function named round. In the Python shell, run each function call below and record the result:

  1. round(24.2)
  2. round(24.5)
  3. round(24.9)
  4. round(1.234567, 2)
  5. round(1.234567, 3)