Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

1.5 Number basics

Learning objectives

By the end of this section you should be able to

  • Use arithmetic operators to perform calculations.
  • Explain the precedence of arithmetic operators.

Numeric data types

Python supports two basic number formats, integer and floating-point. An integer represents a whole number, and a floating-point format represents a decimal number. The format a language uses to represent data is called a data type. In addition to integer and floating-point types, programming languages typically have a string type for representing text.

Basic arithmetic

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.

Four basic arithmetic operators exist in Python:

  1. Addition (+)
  2. Subtraction (-)
  3. Multiplication (*)
  4. Division (/)

Operator precedence

When a calculation has multiple operators, each operator is evaluated in order of precedence. Ex: 1 + 2 * 3 is 7 because multiplication takes precedence over addition. However, (1 + 2) * 3 is 9 because parentheses take precedence over multiplication.

Table 1.4 Operator precedence from highest to lowest.
OperatorDescriptionExampleResult
()Parentheses(1 + 2) * 39
**Exponentiation2 ** 416
+, -Positive, negative-math.pi-3.14159
*, /Multiplication, division2 * 36
+, -Addition, subtraction1 + 23

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or any other accessibility standard. Every page is built against an automated accessibility gate, and our target for the published editions is WCAG 2.2 Level AA. If something is unusable, please tell us.