Arithmetic and numeric types in Python

Completed

Expression syntax in Python is straightforward. The operators plus ("+"), minus ("-"), multiply ("*"), and divide or slash ("/") work like they do in other programming languages such as Java or C. For example, enter the following expression in a Python code cell in Visual Studio Code:

2 + 3

You'll get:

5

The order of operations also works as it does in other programming languages (and in math class). Enter this expression:

30 - 4 * 5

The output looks like this:

10

Note what happens when you use division:

7 / 5

The output is:

1.4

Division ("/") always returns a floating-point number, which brings up an important point. Python, like other programming languages, has different numeric types. Integer numbers, such as 1, 3, and 20, have the type int. Numbers like 3.0 or 1.6, which have a fractional component, have the type float.

You can mix numeric types in calculations:

3 * 3.5

The output is:

10.5

Here's another example of mixed numeric types:

7.0 / 5

The output is:

1.4

You can do a type of division that returns an integer. Floor division uses the double-slash ("//") operator, discards any remainders, and returns only an int.

7 // 5

The output is:

1

To calculate only the remainder, use the modulo operator ("%"):

7 % 5

The output is:

2

Use the power ("**") operator for exponents. For example, you can write $5^2$ as:

5 ** 2

The output is:

25

Conversely, $2^5$ would be:

2 ** 5

The output is:

32

Note that the power operator ("**") precedes the negative sign ("-") in the order of operations. So, $-5^2$ is the same as $-\left(5^2\right)$:

-5 ** 2

The output is:

-25

To assert the order of precedence you want, use parentheses ("()"):

(-5) ** 2

The output is:

25

Parentheses can supersede the order of operations in any calculation:

(30 - 4) * 5

The output is:

130