Python Numbers & Math FunctionsGet Certified
What Are Numbers in Python?
Numbers are the values you calculate with: ages, prices, scores, distances, and temperatures. Python has three built-in numeric types. An int is a whole number such as 42 or -7. A float is a number with a decimal point such as 3.14. A complex number has a real and an imaginary part, such as 3 + 4j. The Boolean type bool is a special kind of integer, because True behaves like 1 and False behaves like 0. Python integers have no fixed size limit, so they grow as large as your computer’s memory allows.
- Numeric types:
int,float, andcomplex, plusboolas a subtype ofint. - Arithmetic:
+,-,*,/,//,%, and**. - Float precision: why
0.1 + 0.2is not exactly0.3and how to compare floats safely. - Built-in functions:
abs(),round(),pow(),min(),max(),sum(), anddivmod(). - The
mathmodule: square roots, rounding up and down, logarithms, trigonometry, and constants such aspi. - Formatting and statistics: display numbers cleanly and compute averages with the
statisticsmodule.
Integers and Floats
You create a number by simply writing it. Python decides the type from how it is written: no decimal point gives an int, and a decimal point or an exponent gives a float. For long numbers you may use underscores as visual separators, as in 1_000_000. Scientific notation uses e, so 2.5e3 means 2.5 times 10 to the power 3, which is 2500.0. The built-in type() function shows the type of a value, and isinstance() tests it.
Try It: Numeric Types
Click Test My Code. Then change big to 1_000.0 and run it again to see how the type changes.
True behaves like the number 1.age = 21
price = 19.99
big = 1_000_000
sci = 2.5e3
print(type(age), type(price))
print(big, sci)
print(2 ** 100)
print(isinstance(True, int), True + True)21 has no decimal point, so Python stores it as an int.19.99 has a decimal point, so Python stores it as a float.big is the integer 1000000.2.5e3 means 2.5 times 10 to the power 3. Because it uses e, the result is a float, 2500.0.type() reports the type of each value. The output is <class 'int'> <class 'float'>.1000000 2500.0.2 ** 100 is calculated exactly. The output is 1267650600228229401496703205376.isinstance(True, int) is True, and True + True adds 1 and 1. The output is True 2.Arithmetic Operators
Python has seven arithmetic operators. Normal division / always returns a float, even when the numbers divide evenly. Floor division // divides and rounds the result down to the nearest whole number. The modulo operator % returns the remainder, and the two always fit together: a == (a // b) * b + a % b. The ** operator raises a number to a power, and a power of 0.5 is a square root. Operators follow the usual order: parentheses first, then **, then * / // %, and finally + and -.
a / bis true division and always gives afloat.a // brounds down toward negative infinity, so-17 // 5is-4, not-3.a % btakes the sign ofb, so-17 % 5is3.a ** bis a power. A negative exponent gives a fraction, as in2 ** -1.divmod(a, b)returns the quotient and the remainder together as a pair.- Dividing by zero raises a
ZeroDivisionError.
Try It: The Seven Operators
Click Test My Code. Change b to 0 to see a ZeroDivisionError, then change it back.
divmod() to get the quotient and remainder in one step.a = 17
b = 5
print(a + b, a - b, a * b)
print(a / b, a // b, a % b)
print(-17 // 5, -17 % 5)
print(2 ** 10, 2 ** -1, 9 ** 0.5)
print(divmod(a, b))a refers to the integer 17.b refers to the integer 5.22 12 85.17 / 5 is true division and gives the float 3.4. 17 // 5 gives the whole part 3. 17 % 5 gives the remainder 2. The output is 3.4 3 2.-17 // 5 is -4, because -3.4 rounded down is -4. The remainder must then be 3, because -4 * 5 + 3 equals -17. The output is -4 3.2 ** 10 is 1024. 2 ** -1 is 0.5. 9 ** 0.5 is the square root of 9, which is 3.0. The output is 1024 0.5 3.0.divmod(17, 5) returns both results as a pair. The output is (3, 2).Floating-Point Precision
Computers store floats in binary, and many decimal fractions such as 0.1 cannot be written exactly in binary. The tiny stored error appears when you print the result of a calculation: 0.1 + 0.2 gives 0.30000000000000004. This is not a Python bug. Every programming language that uses standard floats behaves the same way. There are three safe habits:
- Never compare floats with
==. Usemath.isclose(a, b), which allows for a tiny difference. - Round for display. Use
round()or an f-string such as{x:.2f}when you show a result. - Use
Decimalfor money. Thedecimalmodule stores decimal digits exactly.
Converting a float to an integer with int() does not round. It cuts off the decimal part and moves toward zero, so int(7.9) is 7 and int(-7.9) is -7.
Try It: Why 0.1 + 0.2 Is Not 0.3
Click Test My Code. Notice that three different fixes all lead to the answer you would expect.
0.1 + 0.2 and that a direct comparison fails. It then fixes the comparison by rounding, by using math.isclose(), and by using exact Decimal values. The last line compares division with int() conversion.print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
import math
print(math.isclose(0.1 + 0.2, 0.3))
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
print(7 / 2, 7 // 2, int(7.9), int(-7.9))0.1 and 0.2 are slightly off, so the sum is not exactly 0.3. The output is 0.30000000000000004.False.round(..., 2) keeps two decimal places, which removes the tiny error. The output is True.import statement makes the functions of the math module available.math.isclose() returns True when two floats are equal apart from a very small relative difference. The output is True.Decimal class, which stores decimal numbers exactly.0.3.7 / 2 is 3.5 and 7 // 2 is 3. int() cuts off the decimal part toward zero, giving 7 and -7. The output is 3.5 3 7 -7.Built-in Math Functions
Python includes several number functions that need no import. abs() returns the absolute value, the distance from zero. round(x, n) rounds to n decimal places, and a negative n rounds to tens, hundreds, and so on. pow(x, y) is the same as x ** y, and pow(x, y, m) returns the remainder after dividing by m. min(), max(), and sum() work on several values or on a whole list.
Note: Python’sround()uses banker’s rounding. A value exactly halfway between two integers goes to the nearest even number, soround(2.5)is2andround(3.5)is4. This reduces bias when many numbers are rounded.
Try It: abs, round, pow, min, max and sum
Click Test My Code. Predict the output of round(4.5) before you try it.
min(), max(), and sum() on a list. It then calculates the average of the list and applies max() and min() to separate values.print(abs(-7.5), abs(-3))
print(round(3.14159, 2), round(2.5), round(3.5), round(1234, -2))
print(pow(2, 5), pow(2, 5, 7))
nums = [4, 8, 15, 16, 23, 42]
print(min(nums), max(nums), sum(nums))
print(sum(nums) / len(nums))
print(max(3, 9, 5), min("b", "a"))abs() removes the minus sign. The output is 7.5 3.round(3.14159, 2) gives 3.14. round(2.5) gives 2 and round(3.5) gives 4, because a value halfway between two integers goes to the even one. round(1234, -2) rounds to hundreds and gives 1200. The output is 3.14 2 4 1200.pow(2, 5) is 32. With a third argument, pow(2, 5, 7) is the remainder of 32 divided by 7, which is 4. The output is 32 4.nums refers to a list of six integers.min() is 4, max() is 42, and sum() adds all six numbers to give 108. The output is 4 42 108.18.0.max(3, 9, 5) accepts separate values and returns 9. min("b", "a") compares strings alphabetically and returns a. The output is 9 a.The math Module
For more advanced calculations, import the math module with import math. It provides the constants math.pi and math.e, and a large set of functions:
- Roots and powers:
sqrt(x)returns a float square root.isqrt(n)returns the whole-number square root of an integer. - Rounding:
ceil(x)rounds up,floor(x)rounds down, andtrunc(x)cuts off the decimal part. - Number theory:
factorial(n),gcd(a, b)for the greatest common divisor, andlcm(a, b)for the least common multiple. - Logarithms:
log(x)is the natural logarithm,log10(x)uses base 10, andlog2(x)uses base 2. - Trigonometry:
sin(),cos(), andtan()take angles in radians. Useradians()anddegrees()to convert. - Geometry:
hypot(x, y)returns the length of the hypotenuse of a right triangle.
Try It: Functions from the math Module
Click Test My Code. Try math.sqrt(-1) afterwards and read the error message.
import math
print(math.sqrt(144), math.isqrt(17))
print(math.ceil(4.2), math.floor(4.8), math.trunc(-4.8))
print(math.pi, math.e)
print(math.factorial(5), math.gcd(12, 18), math.lcm(4, 6))
print(math.log10(1000), math.log2(8), math.log(math.e))
print(math.hypot(3, 4), round(math.sin(math.radians(30)), 2))import math loads the module. Its functions are then called with the prefix math..math.sqrt(144) returns the float 12.0. math.isqrt(17) returns the integer square root, rounded down, which is 4. The output is 12.0 4.ceil(4.2) is 5, floor(4.8) is 4, and trunc(-4.8) cuts off the decimals to give -4. The output is 5 4 -4.3.141592653589793 2.718281828459045.5! is 120. The greatest common divisor of 12 and 18 is 6. The least common multiple of 4 and 6 is 12. The output is 120 6 12.3.0 3.0 1.0.hypot(3, 4) is 5.0. radians(30) converts degrees to radians, and the sine of 30 degrees is 0.5, which round() cleans up from a tiny float error. The output is 5.0 0.5.Complex Numbers and Number Systems
A complex number is written with a j after the imaginary part, such as 3 + 4j. It has the attributes .real and .imag, and abs(z) returns its magnitude. Python can also write integers in other number systems. Binary literals start with 0b, octal with 0o, and hexadecimal with 0x. The functions bin(), oct(), and hex() convert an integer to text in those systems, and int(text, base) converts back.
Try It: Complex Numbers and Bases
Click Test My Code. Then convert your own number to binary with bin().
z = 3 + 4j
print(z.real, z.imag, abs(z))
print(z * z)
print(bin(10), oct(10), hex(255))
print(int("ff", 16), int("1010", 2))
print(0b1010, 0o17, 0xFF)3 + 4j has a real part of 3 and an imaginary part of 4.abs(z) is the square root of 3 squared plus 4 squared, which is 5. The output is 3.0 4.0 5.0.(3 + 4j) * (3 + 4j) equals 9 + 24j + 16j squared, and j squared is -1. The output is (-7+24j).0b for binary, 0o for octal, and 0x for hexadecimal. The output is 0b1010 0o12 0xff.int("ff", 16) reads the text as hexadecimal and gives 255. int("1010", 2) reads it as binary and gives 10. The output is 255 10.10 15 255.Formatting Numbers
F-strings allow you to control how numbers are displayed, including their decimal places, width, and alignment. You can do this by adding a format specification after the colon inside the curly braces. The most useful ones are:
:,adds thousands separators, as in1,234,567.:.2fshows a fixed number of decimal places, here two.:.1%multiplies by 100 and adds a percent sign.:05dpads an integer with zeros to a width of 5.:band:xshow an integer in binary and hexadecimal.:eshows scientific notation.:>8,:<8,:^8right-align, left-align, and center a value in 8 characters.
Try It: Number Format Specifications
Click Test My Code. Change .2f to .0f and see how the result changes.
price = 1234567.891
rate = 0.075
n = 42
print(f"{price:,.2f}")
print(f"{rate:.1%}")
print(f"{n:05d} {n:b} {n:x}")
print(f"{price:e}")
print(f"[{n:>8}] [{n:<8}] [{n:^8}]")price refers to the float 1234567.891.rate refers to 0.075, which is 7.5 percent.n refers to the integer 42.:, adds commas and .2f keeps two decimals. The output is 1,234,567.89..1% multiplies by 100, keeps one decimal, and adds %. The output is 7.5%.05d pads with zeros to five digits, b shows binary, and x shows hexadecimal. The output is 00042 101010 2a.:e shows one digit before the point, six after it, and the exponent. The output is 1.234568e+06.[ 42] [42 ] [ 42 ].Statistics and Random Numbers
Two more standard modules are often used with numbers. The statistics module calculates mean(), median(), mode(), and the standard deviation with stdev() for a sample or pstdev() for a whole population. The random module produces unpredictable numbers: random.random() returns a float from 0 up to 1, random.randint(a, b) returns an integer from a to b including both ends, and random.choice(list) picks one item. Calling random.seed(n) makes the sequence repeatable, which is useful for testing.
Try It: statistics and random
Click Test My Code. The dice roll changes whenever the seed is changed, so the program checks the range of the result instead of printing the roll.
random.randint() and picks a random color, and checks that each result is a valid one.import statistics
import random
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(data), statistics.median(data))
print(statistics.mode(data), statistics.pstdev(data))
random.seed(7)
dice = random.randint(1, 6)
print(1 <= dice <= 6)
print(random.choice(["red", "green", "blue"]) in ["red", "green", "blue"])statistics module.random module.data refers to a list of eight numbers.5. The middle two sorted values are 4 and 5, so the median is 4.5. The output is 5 4.5.4 appears most often, so it is the mode. The population standard deviation of this set is 2.0. The output is 4 2.0.random.seed(7) starts the random generator from a fixed point, so the sequence is repeatable.random.randint(1, 6) returns a whole number from 1 to 6, including both ends.dice is at least 1 and at most 6. The output is True.random.choice() picks one color from the list, and in confirms that the choice is one of the three colors. The output is True.Try It: A Circle Calculator
The Program Input box is already filled with the radius 5. Click Run Code straight away, then type another radius, such as 2.5, and run it again.
math.pi to calculate the area and the circumference. It prints both values with two decimals, and uses math.ceil() to print the diameter rounded up to a whole number.import math
radius = float(input("Enter the radius: "))
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print(f"Area: {area:.2f}")
print(f"Circumference: {circumference:.2f}")
print(f"Rounded up diameter: {math.ceil(2 * radius)}")math.pi and math.ceil().input() returns the text 5, and float() converts it to the number 5.0.pi * (radius ** 2).Area: 78.54.Circumference: 31.42.math.ceil() returns the whole number 10. The output is Rounded up diameter: 10.Try It: A Compound Interest Calculator
The Program Input box is filled with three lines: 1000, 5, and 10. Click Run Code, then change the values to see how the rate and the number of years affect the result.
principal = float(input("Principal: "))
rate = float(input("Yearly rate (%): "))
years = int(input("Years: "))
amount = principal * (1 + rate / 100) ** years
interest = amount - principal
print(f"Final amount: {amount:,.2f}")
print(f"Interest earned: {interest:,.2f}")1000. float() converts it to 1000.0.5, a yearly rate of 5 percent.10. int() is used because the number of years is a whole number.** years repeats that ten times.:,.2f adds a thousands separator and keeps two decimals. The output is Final amount: 1,628.89.Interest earned: 628.89.Tip: Keep the full precision during a calculation and round only when you display the result. Rounding at every step makes small errors add up.
Common Mistakes with Numbers
- Comparing floats with
==:0.1 + 0.2 == 0.3isFalse. Usemath.isclose(). - Forgetting that
input()returns text:input() + 1raises aTypeError. Convert first withint()orfloat(). - Expecting
/to give an integer:10 / 2is5.0. Use//when you need a whole number. - Surprises with negative floor division:
-7 // 2is-4, because it rounds down, not toward zero. - Forgetting
import math: callingsqrt(16)ormath.sqrt(16)without the import raises aNameError. - Using degrees in trigonometry:
math.sin()expects radians. Convert withmath.radians()first. - Math domain errors:
math.sqrt(-1)andmath.log(0)raise aValueError, because the result is not a real number. - Expecting
round()to always round half up:round(2.5)is2, because ties go to the nearest even number.
Key Takeaways
- Python has
int,float, andcomplexnumbers, and integers can be as large as memory allows. /always returns a float,//rounds down,%gives the remainder, and**is the power.- Floats are stored in binary, so compare them with
math.isclose()and useDecimalfor exact money calculations. abs(),round(),pow(),min(),max(),sum(), anddivmod()need no import.- The
mathmodule addssqrt(),ceil(),floor(), logarithms, trigonometry, and constants such aspi. - F-strings format numbers with separators, decimals, percentages, padding, and alignment.
- The
statisticsandrandommodules cover averages and random choices.
Frequently Asked Questions
What are the number types in Python?
Python has three built-in numeric types: int for whole numbers, float for numbers with a decimal point, and complex for numbers with a real and an imaginary part. The Boolean type bool is a subtype of int, so True equals 1 and False equals 0.
What is the difference between / and // in Python?
The / operator performs true division and always returns a float, so 7 / 2 is 3.5. The // operator performs floor division and rounds the result down to a whole number, so 7 // 2 is 3 and -7 // 2 is -4.
Why does 0.1 + 0.2 not equal 0.3 in Python?
Floats are stored in binary, and numbers such as 0.1 cannot be represented exactly. The small stored error makes 0.1 + 0.2 equal 0.30000000000000004. To compare floats, use math.isclose(), and for exact decimal arithmetic use the decimal module.
How do I round a number in Python?
Use round(x, n) to round to n decimal places, for example round(3.14159, 2) gives 3.14. Use math.ceil() to always round up and math.floor() to always round down. Note that round() sends exact halves to the nearest even number, so round(2.5) is 2.
How do I calculate a square root in Python?
Use math.sqrt(x) after import math, for example math.sqrt(144) returns 12.0. You can also use the power operator, x ** 0.5. For the whole-number square root of an integer, use math.isqrt(n).
How do I get the remainder of a division in Python?
Use the modulo operator %, for example 17 % 5 is 2. To get the quotient and the remainder at the same time, use divmod(17, 5), which returns the pair (3, 2).
How do I convert between int and float in Python?
Use float(x) to convert to a float and int(x) to convert to an integer. The int() function does not round. It cuts off the decimal part, so int(7.9) is 7 and int(-7.9) is -7. Text from input() must be converted with int() or float() before you calculate with it.
How do I format a number with commas or two decimal places in Python?
Use an f-string with a format specification. The expression f”{x:,.2f}” adds thousands separators and shows two decimal places, so 1234567.891 becomes 1,234,567.89. Use f”{x:.1%}” to show a fraction as a percentage.