Numbers
Python has a few numeric data types. It has multiple ways of storing numbers. Which one you use depends on your intended purpose for the number you are saving.
An integer, or int
, is a whole number. It has no decimal point and contains all counting numbers (1, 2, 3, …) as well as their negative counterparts and the number 0. If you were counting the number of people in a room, the number of jellybeans in a jar, or the number of keys on a keyboard you would likely use an integer.
A floating-point number, or a float
, is a decimal number. It can be used to represent fractional quantities as well as precise measurements. If you were measuring the length of your bedroom wall, calculating the average test score of a seventh-grade class, or storing a baseball player’s batting average for the 1998 season you would likely use a float
.
Numbers can be assigned to variables or used literally in a program:
Above we defined an integer and a float as the variables an_int
and a_float
. We printed out the sum of the variable an_int
with the number 3
. We call the number 3 here a literal, meaning it’s actually the number 3
and not a variable with the number 3 assigned to it.
Floating-point numbers can behave in some unexpected ways due to how computers store them. For more information on floating-point numbers and Python, review Python’s documentation on floating-point limitations.
Arithmetic Operations
Python supports different types of arithmetic operations. These operations can be performed on literal numbers, variables, or some combination. The primary arithmetic operators are:
+
for addition-
for subtraction/
for division*
for multiplication
Notice that when we perform division, the result has a decimal place. This is because Python converts all int
s to float
s before performing division. In older versions of Python (2.7 and earlier) this conversion did not happen, and integer division would always round down to the nearest integer.
Division can throw its own special error: ZeroDivisionError
. Python will raise this error when attempting to divide by 0.
Mathematical operations in Python follow the standard mathematical order of operations.
Exponents
Since this operation is so related to multiplication, we use the notation **
.
Space doesn't mean anything inside expressions. But to make code readable and mistakes easy to spot, always use whitespace around operators, like in the example.
Modulo
The modulo operator is indicated by %
and gives the remainder of a division calculation. If the number is divisible, then the result of the modulo operator will be 0.
The modulo operator is useful in programming when we want to perform an action every nth-time the code is run. Can the result of a modulo operation be larger than the divisor? Why or why not?
Last updated
Was this helpful?